Matlab命令模式

    技术2024-12-23  12

    命令模式(Command)将命令封装为对象,实现命令发送者和命令接收者的解耦。线程池、MVC框架用到了命令模式,本文根据以下类图,用matlab实现命令模式。

     

    Invoker.m (传递命令对象Invoker:持有命令对象,要求命令对象执行请求)

    classdef Invoker < handle properties command end methods function setOrder(obj,command) obj.command = command; end function execute(obj) obj.command.execute(); end end end

    Command.m (抽象命令接口Command:定义命令的接口,声明执行的方法)

    classdef Command < handle methods(Abstract) execute(obj); end end

    ConcreteCommand.m (具体的命令对象ConcreteCommand:持有具体的接受者对象,完成具体的具体的命令)

    classdef ConcreteCommand < Command properties receiver end methods function obj = ConcreteCommand(receiver) obj.receiver = receiver; end function execute(obj) obj.receiver.execute(); end end end

    Receiver.m (接受者对象Receiver:接受者对象,真正执行命令的对象)

    classdef Receiver < handle methods function execute(~) disp("Receiver execute"); end end end

    test.m

    r = Receiver(); c = ConcreteCommand(r); i = Invoker(); i.setOrder(c); i.execute();

    参考资料:

    https://blog.csdn.net/wsh622827/article/details/4759368

    https://blog.csdn.net/zhwyj1019/article/details/79758057

    Processed: 0.010, SQL: 9