I have tied up CareTaker and Originator, and shielded the client class (i.e. MementoPattern ) from knowing about Memento. My understanding is that the CareTaker class is responsible for handling the Memento ( or a list of them ).
Please check if the code below represents a correct understanding of the memento design pattern. In a related question I can see that aggregating the Originator in the CareTaker has been approved.
class Memento{
String state;
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
}
class Originator{
String state;
public String getState(){return state;}
public void setState(String state){this.state = state;}
Memento saveStateToMemento()
{
Memento m = new Memento();
m.setState(state);
return m;
}
void restoreStateFromMemento(Memento m)
{
state = m.getState();
}
}
class CareTaker{
Memento m;
Originator o;
public CareTaker(Originator o)
{
this.o = o;
}
public void saveMemento()
{
m= o.saveStateToMemento();
}
public void restoreFromLastMemento()
{
o.restoreStateFromMemento(m);
}
}
public class MementoPattern {
public static void main(String[] args){
Originator o1 = new Originator();
CareTaker ct = new CareTaker(o1);
o1.setState("1");
System.out.println("initial : "+ o1.getState());
ct.saveMemento();
o1.setState("1A");
System.out.println("modified : "+ o1.getState());
ct.restoreFromLastMemento();
System.out.println("restored : "+ o1.getState());
}
}
Aucun commentaire:
Enregistrer un commentaire