Matlab備忘錄模式(Memento)

備忘錄模式(Memento)用於保存一個對象的某個狀態,以便在適當的時候恢復對象。備忘錄模式屬於行爲型模式,主要包括源發器,備忘錄以及負責人。

  • 源發器:普通類,可以創建備忘錄,也可以使用備忘錄恢復狀態。
  • 備忘錄:儲存原發器內部狀態,處理原發器和負責人類,備忘錄不直接和其他類交互。
  • 負責人:保存備忘錄,但是不對備忘錄操作或檢查

存檔、undo 、數據庫的事務管理用到了備忘錄模式。本文參考以下類圖,用matlab語言實現備忘錄模式。

180514.menento.png

Originator.m

classdef Originator < handle
    properties
        state
    end    
    methods
        function mem = createMemento(obj)
            mem = Memento(obj.state);
        end
        function restoreMemento(obj, mem)
            obj.state = mem.state;
        end
    end    
end

Memento.m

classdef Memento < handle & matlab.mixin.Heterogeneous
    properties
        state
    end
    methods
        function obj = Memento(state)
            obj.state = state;
        end
    end
end

CareTaker.m

classdef CareTaker < handle
    properties
        memento = Memento.empty();
    end
    methods
        function add(obj, mem)
            obj.memento(end + 1) = mem;
        end
        function mem = get(obj, index)
            mem = obj.memento(index);
        end
    end    
end

test.m

originator = Originator();
careTaker = CareTaker();
originator.state = "State #1";
originator.state = "State #2";
careTaker.add(originator.createMemento());
originator.state = "State #3";
careTaker.add(originator.createMemento());
originator.state = "State #4";
 
disp("Current State: " + originator.state);    
originator.restoreMemento(careTaker.get(1));
disp("First saved State: " + originator.state);
originator.restoreMemento(careTaker.get(2));
disp("Second saved State: " + originator.state);

運行結果:

參考資料:

https://www.runoob.com/design-pattern/memento-pattern.html

https://blog.csdn.net/qq_40369829/article/details/80370606

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章