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?
Aucun commentaire:
Enregistrer un commentaire