I have a problem using the memento and the command pattern simultaneously. I fully understand the memento pattern is used to save the state of my object on execute before executing the change on the object so that I can return back to the initial object in on unexecute, but the memento pattern is always saving the same reference of the object when I set the state of it in the memento, do I need to clone the object before creating a memento and setting it too it?
Here's what I have:
public class Memento
{
MyObject myObject;
public MyObject getState()
{
return myObject;
}
public void setState(MyObject myObject)
{
this.myObject = myObject;
}
}
Command:
public class ZoomCommand extends Command
{
Image image;
Memento memento
public InsertCharacterCommand(Image image)
{
//instantiate
this.image = image;
}
@Override public void execute()
{
//create Memento before executing
memento = new Memento();
// set the initial zoom level of the image before executing
memento.setState(image);
//set new state
image.zoomIn(image.getZoom() + 1);
}
@Override public void unExecute()
{
// redo go back to initial state of image before zoom, but image has the same zoom level
this.image = memento.getState();
}
}
Image has the same same zoom level in unExecute too, how can I fix this?
Aucun commentaire:
Enregistrer un commentaire