Uploaded by ameon

Практика Отмена 2

advertisement
using System.Collections.Generic;
namespace TodoApplication
{
public class ListModel<TItem>
{
public List<TItem> Items { get; }
public int Limit; private LimitedSizeStack<Result<TItem>> resultStack;
public ListModel(int limit)
{
Items = new List<TItem>();
Limit = limit;
resultStack = new LimitedSizeStack<Result<TItem>>(limit);
}
public void AddItem(TItem item) {
resultStack.Push(new Result<TItem>(0, 0, item));
Items.Add(item);
}
public void RemoveItem(int index) {
resultStack.Push(new Result<TItem>(1, index, Items[index]));
Items.RemoveAt(index);
}
public bool CanUndo() {
return resultStack.Count == 0 ? false : true;
}
public void Undo()
{
if (CanUndo())
{
Result<TItem> resualt = resultStack.Pop();
resualt.BackwardsResult(this);
}
}
}
public class Result<TItem>
{
private readonly int pointer;
private readonly int command;
private readonly TItem element;
public void BackwardsResult(ListModel<TItem> lm)
{
if (command == 0)
lm.Items.RemoveAt(lm.Items.Count - 1);
else
lm.Items.Insert(pointer, element);
}
public Result(int command, int pointer, TItem element)
{
this.command = command;
this.pointer = pointer;
this.element = element;
}
}
}
Download