In this article, we show how to implement the Memento pattern. We will do this in the context of a simple WPF application that tracks fish in a home aquarium. We will intentionally ignore type inheritance and cover this requirement in the second step.
Pattern overview
At the heart of the Memento pattern, we have the following interface:
1public interface IMementoable
2{
3 IMemento SaveToMemento();
4
5 void RestoreMemento(IMemento memento);
6}
Note
This interface is named IOriginator
in the classic Gang-of-Four book. We continue to refer to this object as the originator in the context of this article.
The memento class is typically a private nested class implementing the following interface:
1public interface IMemento
2{
3 IMementoable Originator { get; }
4}
Our objective is to generate the code supporting the SaveToMemento
and RestoreMemento
methods in the following class:
1using Metalama.Patterns.Observability;
2
3[Memento]
4[Observable]
5public partial class Fish
6{
7 public string? Name { get; set; }
8
9 public string? Species { get; set; }
10
11 public DateTime DateAdded { get; set; }
12}
1using System;
2using System.ComponentModel;
3using Metalama.Patterns.Observability;
4
5[Memento]
6[Observable]
7public partial class Fish
8: INotifyPropertyChanged, IMementoable
9{
10private string? _name;
11
12 public string? Name { get { return this._name; } set { if (!object.ReferenceEquals(value, this._name)) { this._name = value; this.OnPropertyChanged("Name"); } } }
13 private string? _species;
14
15 public string? Species { get { return this._species; } set { if (!object.ReferenceEquals(value, this._species)) { this._species = value; this.OnPropertyChanged("Species"); } } }
16 private DateTime _dateAdded;
17
18 public DateTime DateAdded { get { return this._dateAdded; } set { if (this._dateAdded != value) { this._dateAdded = value; this.OnPropertyChanged("DateAdded"); } } }
19 protected virtual void OnPropertyChanged(string propertyName)
20 {
21 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
22 }
23 public void RestoreMemento(IMemento memento)
24 {
25 var typedMemento = (Memento)memento;
26 this.Name = (typedMemento).Name;
27 this.Species = (typedMemento).Species;
28 this.DateAdded = (typedMemento).DateAdded;
29 }
30 public IMemento SaveToMemento()
31 {
32 return new Memento(this);
33 }
34 public event PropertyChangedEventHandler? PropertyChanged;
35
36 private class Memento : IMemento
37 {
38 public Memento(Fish originator)
39 {
40 this.Originator = originator;
41 this.Name = originator.Name;
42 this.Species = originator.Species;
43 this.DateAdded = originator.DateAdded;
44 }
45 public DateTime DateAdded { get; }
46 public string? Name { get; }
47 public IMementoable? Originator { get; }
48 public string? Species { get; }
49 }
50}
Note
This example also uses the [Observable] aspect to implement the INotifyPropertyChanged
interface.
How can we implement this aspect?
Strategizing
The first step is to list all the code operations that we need to perform:
- Add a nested type named
Memento
with the following members:- The
IMemento
interface and itsOriginator
property. - A private field for each field or automatic property of the originator (
IMementoable
) object, copying its name and property. - A constructor that accepts the originator types as an argument and copies its fields and properties to the private fields of the
Memento
object.
- The
- Implement the
IMementoable
interface with the following members:- The
SaveToMemento
method that returns an instance of the newMemento
type (effectively returning a copy of the state of the object). - The
RestoreMemento
method that copies the properties of theMemento
object back to the fields and properties of the originator.
- The
Passing state between BuildAspect and the templates
As always with non-trivial Metalama aspects, our BuildAspect
method performs the code analysis and adds or overrides members using the IAspectBuilder
advising API. Templates implementing the new methods and constructors read this state.
The following state encapsulates the state that is shared between BuildAspect
and the templates:
7[CompileTime]
8private record BuildAspectInfo(
9 // The newly introduced Memento type.
10 INamedType MementoType,
11 // Mapping from fields or properties in the Originator to the corresponding property
12 // in the Memento type.
13 Dictionary<IFieldOrProperty, IProperty> PropertyMap,
14 // The Originator property in the new Memento type.
15 IProperty OriginatorProperty);
16
The crucial part is the PropertyMap
dictionary, which maps fields and properties of the originator class to the corresponding property of the Memento type.
We use the Tags
facility to pass state between BuildAspect
and the templates. At the end of BuildAspect
, we set the tag:
96builder.Tags = new BuildAspectInfo(mementoType.Declaration, propertyMap,
97 originatorProperty.Declaration);
Then, in the templates, we read it:
109var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
For details regarding state sharing, see Sharing state with advice.
Step 1. Introducing the Memento type
The first step is to introduce a nested type named Memento
.
20// Introduce a new private nested class called Memento.
21var mementoType =
22 builder.IntroduceClass(
23 "Memento",
24 buildType: b =>
25 b.Accessibility =
26 Metalama.Framework.Code.Accessibility.Private);
We store the result in a local variable named mementoType
. We will use it to construct the type.
For details regarding type introduction, see Introducing types.
Step 2. Introducing and mapping the properties
We select the mutable fields and automatic properties, except those that have a [MementoIgnore]
attribute.
30var originatorFieldsAndProperties = builder.Target.FieldsAndProperties
31 .Where(p => p is
32 {
33 IsStatic: false,
34 IsAutoPropertyOrField: true,
35 IsImplicitlyDeclared: false,
36 Writeability: Writeability.All
37 })
38 .Where(p =>
39 !p.Attributes.OfAttributeType(typeof(MementoIgnoreAttribute))
40 .Any());
We iterate through this list and create the corresponding public property in the new Memento
type. While doing this, we update the propertyMap
dictionary, mapping the originator type field or property to the Memento
type property.
44// Introduce data properties to the Memento class for each field of the target class.
45var propertyMap = new Dictionary<IFieldOrProperty, IProperty>();
46
47foreach (var fieldOrProperty in originatorFieldsAndProperties)
48{
49 var introducedField = mementoType.IntroduceProperty(
50 nameof(this.MementoProperty),
51 buildProperty: b =>
52 {
53 var trimmedName = fieldOrProperty.Name.TrimStart('_');
54
55 b.Name = trimmedName.Substring(0, 1).ToUpperInvariant() +
56 trimmedName.Substring(1);
57 b.Type = fieldOrProperty.Type;
58 });
59
60 propertyMap.Add(fieldOrProperty, introducedField.Declaration);
61}
Here is the template for these properties:
101[Template] public object? MementoProperty { get; }
102
Step 3. Adding the Memento constructor
Now that we have the properties and the mapping, we can generate the constructor of the Memento
type.
65// Add a constructor to the Memento class that records the state of the originator.
66mementoType.IntroduceConstructor(
67 nameof(this.MementoConstructorTemplate),
68 buildConstructor: b => { b.AddParameter("originator", builder.Target); });
Here is the constructor template. We iterate the PropertyMap
to set the Memento
properties from the originator.
132[Template]
133public void MementoConstructorTemplate()
134{
135 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
136
137 // Set the originator property and the data properties of the Memento.
138 buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0].Value;
139
140 foreach (var pair in buildAspectInfo.PropertyMap)
141 {
142 pair.Value.Value = pair.Key.With(meta.Target.Parameters[0]).Value;
143 }
144}
Step 4. Implementing the IMemento interface in the Memento type
Let's now implement the IMemento
interface in the Memento
nested type. Here is the BuildAspect
code:
72// Implement the IMemento interface on the Memento class and add its members.
73mementoType.ImplementInterface(typeof(IMemento),
74 whenExists: OverrideStrategy.Ignore);
75
76var originatorProperty =
77 mementoType.IntroduceProperty(nameof(this.Originator));
This interface has a single member:
103[Template] public IMementoable? Originator { get; }
104
Step 5. Implementing the IMementoable interface in the originator type
We can finally implement the IMementoable
interface.
81// Implement the rest of the IOriginator interface and its members.
82builder.ImplementInterface(typeof(IMementoable));
83
84builder.IntroduceMethod(
85 nameof(this.SaveToMemento),
86 whenExists: OverrideStrategy.Override,
87 args: new { mementoType = mementoType.Declaration });
88
89builder.IntroduceMethod(
90 nameof(this.RestoreMemento),
91 whenExists: OverrideStrategy.Override);
Here are the interface members:
105[Template]
106public IMemento SaveToMemento()
107{
109 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
111
112 // Invoke the constructor of the Memento class and pass this object as the originator.
113 return buildAspectInfo.MementoType.Constructors.Single()
114 .Invoke((IExpression)meta.This)!;
115}
116
117[Template]
118public void RestoreMemento(IMemento memento)
119{
120 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
121
122 var typedMemento = meta.Cast(buildAspectInfo.MementoType, memento);
123
124 // Set fields of this instance to the values stored in the Memento.
125 foreach (var pair in buildAspectInfo.PropertyMap)
126 {
127 pair.Key.Value = pair.Value.With((IExpression)typedMemento).Value;
128 }
129}
130
Note again the use of the property mapping in the RestoreMemento
method.
Complete aspect
Let's now put all the bits together. Here is the complete source code of our aspect, MementoAttribute
.
1using Metalama.Framework.Advising;
2using Metalama.Framework.Aspects;
3using Metalama.Framework.Code;
4
5public sealed class MementoAttribute : TypeAspect
6{
7 [CompileTime]
8 private record BuildAspectInfo(
9 // The newly introduced Memento type.
10 INamedType MementoType,
11 // Mapping from fields or properties in the Originator to the corresponding property
12 // in the Memento type.
13 Dictionary<IFieldOrProperty, IProperty> PropertyMap,
14 // The Originator property in the new Memento type.
15 IProperty OriginatorProperty);
16
17 public override void BuildAspect(IAspectBuilder<INamedType> builder)
18 {
19 //
20 // Introduce a new private nested class called Memento.
21 var mementoType =
22 builder.IntroduceClass(
23 "Memento",
24 buildType: b =>
25 b.Accessibility =
26 Metalama.Framework.Code.Accessibility.Private);
27 //
28
29 //
30 var originatorFieldsAndProperties = builder.Target.FieldsAndProperties
31 .Where(p => p is
32 {
33 IsStatic: false,
34 IsAutoPropertyOrField: true,
35 IsImplicitlyDeclared: false,
36 Writeability: Writeability.All
37 })
38 .Where(p =>
39 !p.Attributes.OfAttributeType(typeof(MementoIgnoreAttribute))
40 .Any());
41 //
42
43 //
44 // Introduce data properties to the Memento class for each field of the target class.
45 var propertyMap = new Dictionary<IFieldOrProperty, IProperty>();
46
47 foreach (var fieldOrProperty in originatorFieldsAndProperties)
48 {
49 var introducedField = mementoType.IntroduceProperty(
50 nameof(this.MementoProperty),
51 buildProperty: b =>
52 {
53 var trimmedName = fieldOrProperty.Name.TrimStart('_');
54
55 b.Name = trimmedName.Substring(0, 1).ToUpperInvariant() +
56 trimmedName.Substring(1);
57 b.Type = fieldOrProperty.Type;
58 });
59
60 propertyMap.Add(fieldOrProperty, introducedField.Declaration);
61 }
62 //
63
64 //
65 // Add a constructor to the Memento class that records the state of the originator.
66 mementoType.IntroduceConstructor(
67 nameof(this.MementoConstructorTemplate),
68 buildConstructor: b => { b.AddParameter("originator", builder.Target); });
69 //
70
71 //
72 // Implement the IMemento interface on the Memento class and add its members.
73 mementoType.ImplementInterface(typeof(IMemento),
74 whenExists: OverrideStrategy.Ignore);
75
76 var originatorProperty =
77 mementoType.IntroduceProperty(nameof(this.Originator));
78 //
79
80 //
81 // Implement the rest of the IOriginator interface and its members.
82 builder.ImplementInterface(typeof(IMementoable));
83
84 builder.IntroduceMethod(
85 nameof(this.SaveToMemento),
86 whenExists: OverrideStrategy.Override,
87 args: new { mementoType = mementoType.Declaration });
88
89 builder.IntroduceMethod(
90 nameof(this.RestoreMemento),
91 whenExists: OverrideStrategy.Override);
92 //
93
94 // Pass the state to the templates.
95 //
96 builder.Tags = new BuildAspectInfo(mementoType.Declaration, propertyMap,
97 originatorProperty.Declaration);
98 //
99 }
100
101 [Template] public object? MementoProperty { get; }
102
103 [Template] public IMementoable? Originator { get; }
104
105 [Template]
106 public IMemento SaveToMemento()
107 {
108 //
109 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
110 //
111
112 // Invoke the constructor of the Memento class and pass this object as the originator.
113 return buildAspectInfo.MementoType.Constructors.Single()
114 .Invoke((IExpression)meta.This)!;
115 }
116
117 [Template]
118 public void RestoreMemento(IMemento memento)
119 {
120 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
121
122 var typedMemento = meta.Cast(buildAspectInfo.MementoType, memento);
123
124 // Set fields of this instance to the values stored in the Memento.
125 foreach (var pair in buildAspectInfo.PropertyMap)
126 {
127 pair.Key.Value = pair.Value.With((IExpression)typedMemento).Value;
128 }
129 }
130
131 //
132 [Template]
133 public void MementoConstructorTemplate()
134 {
135 var buildAspectInfo = (BuildAspectInfo)meta.Tags.Source!;
136
137 // Set the originator property and the data properties of the Memento.
138 buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0].Value;
139
140 foreach (var pair in buildAspectInfo.PropertyMap)
141 {
142 pair.Value.Value = pair.Key.With(meta.Target.Parameters[0]).Value;
143 }
144 }
145 //
146}
This implementation does not support type inheritance, i.e., a memento-able object cannot inherit from another memento-able object. In the next article, we will see how to support type inheritance.