猿问

如何将纪念图案与撤消功能结合使用

我在同时使用纪念品和命令模式时遇到问题。我完全理解纪念图案用于在对对象执行更改之前在执行时保存对象的状态,以便我可以在未执行时返回到初始对象,但是当我在纪念品中设置对象的状态时,纪念图案总是保存对象的相同引用, 在创建纪念品并设置它之前,我是否需要克隆对象?


这是我所拥有的:


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();

    }

}

图像在“自动执行”中也具有相同的缩放级别,我该如何解决此问题?


慕无忌1623718
浏览 105回答 1
1回答

炎炎设计

是的,您需要克隆对象。像往常一样,在互联网上找到的例子相当贫乏,但重构大师有一个可行的例子。他们用于加载和保存对象的代码如下所示: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.");    }}请注意,它不处理引用。相反,它提供了一个用于保存和恢复整个对象状态的方案。本质上,它是 Java 对象的深层副本。
随时随地看视频慕课网APP

相关分类

Java
我要回答