策略模式的意图是定义一系列算法,把它们一个一个封装起来,并且使它们可以互相替换。通常每个策略算法不可抽象再分。本人仿照https://www.runoob.com/design-pattern/strategy-pattern.html所给的例子,用Matlab代码对其进行实现
Strategy.m
classdef Strategy < handle methods(Abstract) doOperation(~,~,~); end end
OperationAdd.m
classdef OperationAdd < Strategy methods function res = doOperation(~,num1,num2) res = num1 + num2; end end end
OperationMultiply.m
classdef OperationMultiply < Strategy methods function res = doOperation(~,num1,num2) res = num1 * num2; end end end
Context.m
classdef Context < handle properties strategy end methods function obj = Context(strategy) obj.strategy = strategy; end function res = executeStrategy(obj,num1,num2) res = obj.strategy.doOperation(num1,num2); end end end
测试代码:
context = Context(OperationAdd()); disp("2 + 3 = " + context.executeStrategy(2, 3)); context =Context(OperationMultiply()); disp("2 * 3 = " + context.executeStrategy(2, 3));