第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將紀念圖案與撤消功能結合使用

如何將紀念圖案與撤消功能結合使用

慕無忌1623718 2022-09-14 17:32:13
我在同時使用紀念品和命令模式時遇到問題。我完全理解紀念圖案用于在對對象執(zhí)行更改之前在執(zhí)行時保存對象的狀態(tài),以便我可以在未執(zhí)行時返回到初始對象,但是當我在紀念品中設置對象的狀態(tài)時,紀念圖案總是保存對象的相同引用, 在創(chuàng)建紀念品并設置它之前,我是否需要克隆對象?這是我所擁有的: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();    }}圖像在“自動執(zhí)行”中也具有相同的縮放級別,我該如何解決此問題?
查看完整描述

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.");

    }

}

請注意,它不處理引用。相反,它提供了一個用于保存和恢復整個對象狀態(tài)的方案。本質上,它是 Java 對象的深層副本。


查看完整回答
反對 回復 2022-09-14
  • 1 回答
  • 0 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號