Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace TodoApplication
- {
- class History<TItem>
- {
- public History(Operation operation, int index, TItem item)
- {
- Operation = operation;
- Index = index;
- Item = item;
- }
- public Operation Operation;
- public int Index;
- public TItem Item;
- }
- public enum Operation
- {
- Add,
- Remove
- }
- public class ListModel<TItem>
- {
- public List<TItem> Items { get; }
- public readonly int Limit;
- private readonly LimitedSizeStack<History<TItem>> operationStack;
- public ListModel(int limit)
- {
- Items = new List<TItem>();
- Limit = limit;
- operationStack = new LimitedSizeStack<History<TItem>>(limit);
- }
- public void AddItem(TItem item)
- {
- var newAddCommand = new History<TItem>(Operation.Add, Items.Count, item);
- operationStack.Push(newAddCommand);
- Items.Add(item);
- }
- public void RemoveItem(int index)
- {
- var newRemoveCommand = new History<TItem>(Operation.Remove, index, Items[index]);
- operationStack.Push(newRemoveCommand);
- Items.RemoveAt(index);
- }
- public bool CanUndo()
- {
- return operationStack.Count > 0;
- }
- public void Undo()
- {
- History<TItem> deepestCommand = operationStack.Pop();
- switch (deepestCommand.Operation)
- {
- case Operation.Add:
- Items.RemoveAt(deepestCommand.Index);
- break;
- case Operation.Remove:
- Items.Insert(deepestCommand.Index, deepestCommand.Item);
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement