命令模式(Command)將命令封裝爲對象,實現命令發送者和命令接收者的解耦。線程池、MVC框架用到了命令模式,本文根據如下類圖,用matlab實現命令模式。框架
Invoker.m (傳遞命令對象Invoker:持有命令對象,要求命令對象執行請求).net
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:接受者對象,真正執行命令的對象)blog
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();
參考資料:get