当前位置: 移动技术网 > IT编程>软件设计>设计模式 > Matlab备忘录模式

Matlab备忘录模式

2019年06月04日  | 移动技术网IT编程  | 我要评论

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

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

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

参考资料:


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网