Open sandboxFocusImprove this doc

Memento example, step 1: a basic aspect

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:

Source Code


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}
Transformed Code
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:

  1. Add a nested type named Memento with the following members:
    • The IMemento interface and its Originator 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.
  2. Implement the IMementoable interface with the following members:
    • The SaveToMemento method that returns an instance of the new Memento type (effectively returning a copy of the state of the object).
    • The RestoreMemento method that copies the properties of the Memento object back to the fields and properties of the originator.

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]
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 );

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:

88        builder.Tags = new BuildAspectInfo( mementoType.Declaration, propertyMap, 
89            originatorProperty.Declaration ); 

Then, in the templates, we read it:

99        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!; 
100        

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.

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 ); 

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.

28        var originatorFieldsAndProperties = builder.Target.FieldsAndProperties 
29            .Where( p => p is
30            {
31                IsStatic: false,
32                IsAutoPropertyOrField: true,
33                IsImplicitlyDeclared: false,
34                Writeability: Writeability.All
35            } )
36            .Where( p =>
37                !p.Attributes.OfAttributeType( typeof(MementoIgnoreAttribute) )
38                    .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.

41        var propertyMap = new Dictionary<IFieldOrProperty, IProperty>(); 
42
43        foreach ( var fieldOrProperty in originatorFieldsAndProperties )
44        {
45            var introducedField = mementoType.IntroduceProperty(
46                nameof(this.MementoProperty),
47                buildProperty: b =>
48                {
49                    var trimmedName = fieldOrProperty.Name.TrimStart( '_' );
50
51                    b.Name = trimmedName.Substring( 0, 1 ).ToUpperInvariant() +
52                             trimmedName.Substring( 1 );
53                    b.Type = fieldOrProperty.Type;
54                } );
55
56            propertyMap.Add( fieldOrProperty, introducedField.Declaration );
57        } 

Here is the template for these properties:

92    [Template] public object? MementoProperty { get; }

Step 3. Adding the Memento constructor

Now that we have the properties and the mapping, we can generate the constructor of the Memento type.

60        mementoType.IntroduceConstructor( 
61            nameof(this.MementoConstructorTemplate),
62            buildConstructor: b =>
63            {
64                b.AddParameter( "originator", builder.Target );
65            } ); 

Here is the constructor template. We iterate the PropertyMap to set the Memento properties from the originator.

121    [Template] 
122    public void MementoConstructorTemplate()
123    {
124        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
125
126        // Set the originator property and the data properties of the Memento.
127        buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0].Value;
128
129        foreach ( var pair in buildAspectInfo.PropertyMap )
130        {
131            pair.Value.Value = pair.Key.With( meta.Target.Parameters[0] ).Value;
132        }
133    } 

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:

70            whenExists: OverrideStrategy.Ignore ); 
71
72        var originatorProperty =
73            mementoType.IntroduceProperty( nameof(this.Originator) ); 

This interface has a single member:

94    [Template] public IMementoable? Originator { get; }

Step 5. Implementing the IMementoable interface in the originator type

We can finally implement the IMementoable interface.

76        builder.ImplementInterface( typeof(IMementoable) ); 
77
78        builder.IntroduceMethod(
79            nameof(this.SaveToMemento),
80            whenExists: OverrideStrategy.Override,
81            args: new { mementoType = mementoType.Declaration } );
82
83        builder.IntroduceMethod(
84            nameof(this.RestoreMemento),
85            whenExists: OverrideStrategy.Override ); 

Here are the interface members:

96    [Template]
97    public IMemento SaveToMemento()
98    {
99        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!; 
100        
101
102        // Invoke the constructor of the Memento class and pass this object as the originator.
103        return buildAspectInfo.MementoType.Constructors.Single()
104            .Invoke( (IExpression) meta.This )!;
105    }

107    [Template]
108    public void RestoreMemento( IMemento memento )
109    {
110        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
111
112        var typedMemento = meta.Cast( buildAspectInfo.MementoType, memento );
113
114        // Set fields of this instance to the values stored in the Memento.
115        foreach ( var pair in buildAspectInfo.PropertyMap )
116        {
117            pair.Key.Value = pair.Value.With( (IExpression) typedMemento ).Value;
118        }
119    }

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        var originatorFieldsAndProperties = builder.Target.FieldsAndProperties 
29            .Where( p => p is
30            {
31                IsStatic: false,
32                IsAutoPropertyOrField: true,
33                IsImplicitlyDeclared: false,
34                Writeability: Writeability.All
35            } )
36            .Where( p =>
37                !p.Attributes.OfAttributeType( typeof(MementoIgnoreAttribute) )
38                    .Any() ); 
39
40        // Introduce data properties to the Memento class for each field of the target class.
41        var propertyMap = new Dictionary<IFieldOrProperty, IProperty>(); 
42
43        foreach ( var fieldOrProperty in originatorFieldsAndProperties )
44        {
45            var introducedField = mementoType.IntroduceProperty(
46                nameof(this.MementoProperty),
47                buildProperty: b =>
48                {
49                    var trimmedName = fieldOrProperty.Name.TrimStart( '_' );
50
51                    b.Name = trimmedName.Substring( 0, 1 ).ToUpperInvariant() +
52                             trimmedName.Substring( 1 );
53                    b.Type = fieldOrProperty.Type;
54                } );
55
56            propertyMap.Add( fieldOrProperty, introducedField.Declaration );
57        } 
58
59        // Add a constructor to the Memento class that records the state of the originator.
60        mementoType.IntroduceConstructor( 
61            nameof(this.MementoConstructorTemplate),
62            buildConstructor: b =>
63            {
64                b.AddParameter( "originator", builder.Target );
65            } ); 
66
67
68        // Implement the IMemento interface on the Memento class and add its members.   
69        mementoType.ImplementInterface( typeof(IMemento),
70            whenExists: OverrideStrategy.Ignore ); 
71
72        var originatorProperty =
73            mementoType.IntroduceProperty( nameof(this.Originator) ); 
74
75        // Implement the rest of the IOriginator interface and its members.
76        builder.ImplementInterface( typeof(IMementoable) ); 
77
78        builder.IntroduceMethod(
79            nameof(this.SaveToMemento),
80            whenExists: OverrideStrategy.Override,
81            args: new { mementoType = mementoType.Declaration } );
82
83        builder.IntroduceMethod(
84            nameof(this.RestoreMemento),
85            whenExists: OverrideStrategy.Override ); 
86
87        // Pass the state to the templates.
88        builder.Tags = new BuildAspectInfo( mementoType.Declaration, propertyMap, 
89            originatorProperty.Declaration ); 
90    }
91
92    [Template] public object? MementoProperty { get; }
93
94    [Template] public IMementoable? Originator { get; }
95
96    [Template]
97    public IMemento SaveToMemento()
98    {
99        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!; 
100        
101
102        // Invoke the constructor of the Memento class and pass this object as the originator.
103        return buildAspectInfo.MementoType.Constructors.Single()
104            .Invoke( (IExpression) meta.This )!;
105    }
106
107    [Template]
108    public void RestoreMemento( IMemento memento )
109    {
110        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
111
112        var typedMemento = meta.Cast( buildAspectInfo.MementoType, memento );
113
114        // Set fields of this instance to the values stored in the Memento.
115        foreach ( var pair in buildAspectInfo.PropertyMap )
116        {
117            pair.Key.Value = pair.Value.With( (IExpression) typedMemento ).Value;
118        }
119    }
120
121    [Template] 
122    public void MementoConstructorTemplate()
123    {
124        var buildAspectInfo = (BuildAspectInfo) meta.Tags.Source!;
125
126        // Set the originator property and the data properties of the Memento.
127        buildAspectInfo.OriginatorProperty.Value = meta.Target.Parameters[0].Value;
128
129        foreach ( var pair in buildAspectInfo.PropertyMap )
130        {
131            pair.Value.Value = pair.Key.With( meta.Target.Parameters[0] ).Value;
132        }
133    } 
134}

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.