I've been studying design patterns from GOF for a few weeks, especially in C#, and I'm struggling with Memento Pattern. I know there is a lot of C# implementations on the web, but I came with my own version of it. The question is: although it diverges from GOF UML, is it still reasonable and valid considering SOLID principles?
What is your opinion?
interface IMemento
{
List<IMemento> Mementos { get; set; }
void SetMemento();
IMemento? GetMemento(uint index);
IMemento? GetPreviousMemento() => (Mementos.Count > 1) ? Mementos[Mementos.Count - 2] : null; // Optional method
}
class Subject : IMemento // Originator
{
public Subject(string prop1, int prop2)
{
Prop1 = prop1;
Prop2 = prop2;
SetMemento();
}
private string _prop1;
public string Prop1
{
get => _prop1;
set
{
_prop1 = value;
SetMemento();
}
}
private int _prop2;
public int Prop2
{
get => _prop2;
set
{
_prop2 = value;
SetMemento();
}
}
public List<IMemento> Mementos { get; set; } = new List<IMemento>(); // Caretaker
public void Method1() { }
public void Method2() { }
public void SetMemento() => Mementos.Add((IMemento)MemberwiseClone());
public IMemento? GetMemento(uint index) => (index < Mementos.Count) ? Mementos[(int)index] : null;
public IMemento? GetPreviousMemento() => (Mementos.Count > 1) ? Mementos[Mementos.Count - 2] : null;
}
I've already tested and from my point of view, the only big problem can be with memory consume, but that is a normal issue when it comes to Memento and it can be solved with Flyweight, for example.
Aucun commentaire:
Enregistrer un commentaire