同时使用memento和命令模式有问题。我完全理解memento模式用于在执行对象之前保存对象的状态,这样我就可以返回到unexecute上的初始对象,但是当我在memento中设置对象的状态时,memento模式总是保存对象的相同引用,在创建备忘录和设置它之前是否需要克隆对象?
我现在拥有的是:
public class Memento
{
MyObject myObject;
public MyObject getState()
{
return myObject;
}
public void setState(MyObject myObject)
{
this.myObject = myObject;
}
}命令:
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();
}
}图像在unExecute中也有相同的缩放级别,我如何解决这个问题?
发布于 2019-04-01 19:31:14
是的,你需要克隆这个物体。
和往常一样,互联网上的例子相当贫乏,但重构师有一个可行的例子。它们用于加载和保存对象的代码如下所示:
public String backup() {
try {
ByteArrayOutputStream b= new ByteArrayOutputStream();
ObjectOutputStream o= new ObjectOutputStream(b);
o.writeObject(this.allShapes);
o.close();
return Base64.getEncoder().encodeToString(b.toByteArray());
} catch (IOException e) {
return "";
}
}
public void restore(String state) {
try {
byte[] data = Base64.getDecoder().decode(state);
ObjectInputStream o = new ObjectInputStream(new ByteArrayInputStream(data));
this.allShapes = (CompoundShape) o.readObject();
o.close();
} catch (ClassNotFoundException e) {
System.out.print("ClassNotFoundException occurred.");
} catch (IOException e) {
System.out.print("IOException occurred.");
}
}注意,它不处理引用。相反,它提供了一种保存和恢复整个对象状态的方案。本质上,它是对象的一个深拷贝。
https://stackoverflow.com/questions/55462044
复制相似问题