Repository navigation
Expand file tree
/
Copy pathCommand.cs
More file actions
83 lines (72 loc) · 2.54 KB
/
Copy pathCommand.cs
File metadata and controls
83 lines (72 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
namespace CSharpExercises.Patterns;
/// <summary>
/// Command: each operation is an object that knows how to do and undo itself. The history only sees the interface,
/// so undo/redo, macros (a command made of commands) and logging work for any operation, including ones added later.
/// </summary>
public interface IUndoableCommand
{
string Description { get; }
void Execute();
void Undo();
}
public sealed class Calculator
{
public decimal Value { get; set; }
}
public sealed class AddCommand(Calculator calculator, decimal amount) : IUndoableCommand
{
public string Description => $"add {amount}";
public void Execute() => calculator.Value += amount;
public void Undo() => calculator.Value -= amount;
}
/// <summary>Multiplying by zero can't be undone by dividing, so this command remembers the previous value instead.</summary>
public sealed class MultiplyCommand(Calculator calculator, decimal factor) : IUndoableCommand
{
private decimal _before;
public string Description => $"multiply by {factor}";
public void Execute()
{
_before = calculator.Value;
calculator.Value *= factor;
}
public void Undo() => calculator.Value = _before;
}
/// <summary>A composite command: undone as one step, in reverse order.</summary>
public sealed class MacroCommand(string name, params IUndoableCommand[] steps) : IUndoableCommand
{
public string Description => $"{name} ({string.Join(", ", steps.Select(s => s.Description))})";
public void Execute()
{
foreach (var step in steps) step.Execute();
}
public void Undo()
{
for (var i = steps.Length - 1; i >= 0; i--) steps[i].Undo();
}
}
public sealed class CommandHistory
{
private readonly Stack<IUndoableCommand> _undo = new();
private readonly Stack<IUndoableCommand> _redo = new();
public bool CanUndo => _undo.Count > 0;
public bool CanRedo => _redo.Count > 0;
public IEnumerable<string> Log => _undo.Reverse().Select(c => c.Description);
public void Execute(IUndoableCommand command)
{
command.Execute();
_undo.Push(command);
_redo.Clear(); // a new action makes the redo branch meaningless
}
public void Undo()
{
if (!_undo.TryPop(out var command)) throw new InvalidOperationException("Nothing to undo.");
command.Undo();
_redo.Push(command);
}
public void Redo()
{
if (!_redo.TryPop(out var command)) throw new InvalidOperationException("Nothing to redo.");
command.Execute();
_undo.Push(command);
}
}