Matlab备忘录模式

备忘录模式(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);

参考资料:

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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值