Matlab备忘录模式

备忘录模式(Memento)用于保存一个对象的某个状态,以便在适当的时候恢复对象。备忘录模式属于行为型模式,主要包括源发器,备忘录以及负责人。源发器:普通类,可以创建备忘录,也可以使用备忘录恢复状态。备忘录:储存原发器内部状态,处理原发器和负责人类,备忘录不直接和其他类交互。负责人:保存备忘录,但是不对备忘录操作或检查

存档、undo 、数据库的事务管理用到了备忘录模式。本文参考以下类图,用matlab语言实现备忘录模式。

Matlab备忘录模式_第1张图片

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


你可能感兴趣的:(技术)