-
Notifications
You must be signed in to change notification settings - Fork 31
/
Memento.cs
88 lines (72 loc) · 2.23 KB
/
Memento.cs
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
84
85
86
87
88
namespace DesignPatterns.Behavioral;
public class Memento
{
[Fact]
public void Execute()
{
var fileMemory = new FileMemory();
// Set the initial state of the originator
var file = new File
{
Author = "John Doe",
Content = "",
Title = "The mermaid"
};
// Save the state
fileMemory.AddState(file.CreateState());
FileState initialState = fileMemory.GetLastState();
Assert.Equal(file.Content, initialState.Content);
// Change the state of the originator
file.Content = "Once upon a time.";
Assert.NotEqual(file.Content, initialState.Content);
// Restore the state to the previous one.
file.RestoreState(initialState);
Assert.Equal("", file.Content);
}
/// <summary>
/// Originator
/// </summary>
/// <remarks>
/// - Creates a memento containing a snapshot of its current internal state.
/// - Uses the memento to restore its internal state
/// </remarks>
public class File
{
public string Author { get; set; }
public string Content { get; set; }
public string Title { get; set; }
public FileState CreateState() => new(Content);
public void RestoreState(FileState state)
{
Content = state.Content;
}
}
/// <summary>
/// Memento
/// </summary>
/// <remarks>
/// - Stores internal state of the Originator object.
/// - The memento may store as much or as little of the originator's internal state as necessary at its originator's
/// discretion.
/// </remarks>
public class FileState(string content)
{
public string Content { get; } = content;
}
/// <summary>
/// Caretaker
/// </summary>
/// <remarks>
/// - Is responsible for the memento's safekeeping.
/// - Never operates on or examines the contents of a memento.
/// </remarks>
public class FileMemory
{
private readonly Stack<FileState> _fileStates = [];
public void AddState(FileState fileState)
{
_fileStates.Push(fileState);
}
public FileState GetLastState() => _fileStates.Peek();
}
}