-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommand Pattern.cs
More file actions
80 lines (67 loc) · 1.83 KB
/
Command Pattern.cs
File metadata and controls
80 lines (67 loc) · 1.83 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
Command Pattern
Definition:
Encapsulates a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations.
Use Case:
Implementing an undo functionality in a text editor.
Example:
csharp
Copy code
// Command Interface
public interface ICommand
{
void Execute();
void Undo();
}
// Concrete Command
public class AddTextCommand : ICommand
{
private readonly Document _document;
private readonly string _text;
public AddTextCommand(Document document, string text)
{
_document = document;
_text = text;
}
public void Execute() => _document.AddText(_text);
public void Undo() => _document.RemoveText(_text);
}
// Receiver
public class Document
{
private readonly StringBuilder _content = new StringBuilder();
public void AddText(string text) => _content.Append(text);
public void RemoveText(string text) => _content.Remove(_content.Length - text.Length, text.Length);
public override string ToString() => _content.ToString();
}
// Invoker
public class TextEditor
{
private readonly Stack<ICommand> _commandHistory = new Stack<ICommand>();
public void ExecuteCommand(ICommand command)
{
command.Execute();
_commandHistory.Push(command);
}
public void Undo()
{
if (_commandHistory.Count > 0)
{
var command = _commandHistory.Pop();
command.Undo();
}
}
}
// Usage
class Program
{
static void Main()
{
var document = new Document();
var textEditor = new TextEditor();
var command = new AddTextCommand(document, "Hello, World!");
textEditor.ExecuteCommand(command);
Console.WriteLine(document); // Outputs: Hello, World!
textEditor.Undo();
Console.WriteLine(document); // Outputs: (empty)
}
}