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?
Encapsulation doesn't mean that you shouldn't be able to access the data at all, you just shouldn't be able to access it directly. You should only be able to access it via public methods :)
This link is probably able to explain it better than i am:
https://www.geeksforgeeks.org/encapsulation-in-java/
So encapsulation is kept in your code example, since the state can only be retrieved via a public get method.