策略模式的意圖是定義一系列演算法,把它們一個一個封裝起來,並且使它們可以互相替換。通常每個策略演算法不可抽象再分。本人仿照https://www.runoob.com/design-pattern/strategy-pattern.html所給的例子,用Matlab代碼對其進行實現 Strategy.m ...
策略模式的意圖是定義一系列演算法,把它們一個一個封裝起來,並且使它們可以互相替換。通常每個策略演算法不可抽象再分。本人仿照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));