欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Matlab策略模式

程序员文章站 2022-04-14 15:36:19
策略模式的意图是定义一系列算法,把它们一个一个封装起来,并且使它们可以互相替换。通常每个策略算法不可抽象再分。本人仿照https://www.runoob.com/design-pattern/strategy-pattern.html所给的例子,用Matlab代码对其进行实现 Strategy.m ......

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