为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕无忌1623718 2022-09-14 17:32:13
我在同时使用纪念品和命令模式时遇到问题。我完全理解纪念图案用于在对对象执行更改之前在执行时保存对象的状态,以便我可以在未执行时返回到初始对象,但是当我在纪念品中设置对象的状态时,纪念图案总是保存对象的相同引用, 在创建纪念品并设置它之前,我是否需要克隆对象?这是我所拥有的: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();    }}图像在“自动执行”中也具有相同的缩放级别,我该如何解决此问题?
查看完整描述

1 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

是的,您需要克隆对象。


像往常一样,在互联网上找到的例子相当贫乏,但重构大师有一个可行的例子。他们用于加载和保存对象的代码如下所示:


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 对象的深层副本。


查看完整回答
反对 回复 2022-09-14
  • 1 回答
  • 0 关注
  • 103 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号