Matlab策略模式

策略模式的意图是定义一系列算法,把它们一个一个封装起来,并且使它们可以互相替换。通常每个策略算法不可抽象再分。本人仿照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));

posted on 2019-05-17 10:08  sw-lab  阅读(428)  评论(0编辑  收藏  举报

导航