Across the internet I come across with examples of implementation of memento pattern which I consider are fully incorrect. They can be written in both Java and C#.
Here a several of them
- Incorrect implementation of Memento pattern 1
- Incorrect implementation of Memento pattern 2
- Incorrect implementation of Memento pattern 3
The code:
public class Originator
{
private string _state; //the private field of originator that shouldn't be exposed!!!!
public Memento CreateMemento()
{
return new Memento(_state);
}
public void SetMemento(Memento memento)
{
_state = memento.GetState();
}
}
public class Memento
{
private string _state;
public Memento(string state)
{
_state = state;
}
public string GetState()
{
return _state; // here caretaker can access to private field of originator!!!
}
}
public class Caretaker
{
public Memento Memento { get; set; }
}
In code I left comments that should describe situation.
The caretaker class can read private field of originator through memento that violates one of the main principles of memento pattern:
The object's encapsulation must not be violated.
So the question is am I right?
Yes, you are right: the examples are all incorrect implementations of the Memento design pattern, because the
Memento
class exposes its internal dependency through a public method. As you noted, this allows theCaretaker
(or any other class) to gain private information about theOriginator
.Previous answers focus on the state of the internal field and whether the
Memento
state can vary independently of theOriginator
. But encapsulation can be violated in more ways than by exposing state. It can also be violated by exposing dependencies. The public getter method exposes the dependency thatOriginator
has onString
.I wish I could say that misinformation is unusual regarding design patterns; but you will find inaccurate and misleading articles about design patterns across the Internet, including here on SO and on Wikipedia.
I happen to like https://refactoring.guru/design-patterns/memento but it's never a bad idea to crosscheck against the GoF book.