strategy pattern in matlab

The Strategy Pattern is a behavioral design pattern that allows selecting an algorithm at runtime. To implement the Strategy Pattern in MATLAB, you can follow these steps:

  1. Define an abstract Strategy class that specifies the interface for the algorithm. This class should have an abstract method that contains the algorithm to be executed.
main.m
classdef (Abstract) Strategy
   methods (Abstract)
      result = algorithm(obj, input)
   end
end
99 chars
6 lines
  1. Define concrete Strategy classes that implement the algorithm. Each concrete class should inherit from the abstract Strategy class and implement the algorithm method.
main.m
classdef ConcreteStrategyA < Strategy
   methods
      function result = algorithm(obj, input)
         result = input * 2;
      end
   end
end

classdef ConcreteStrategyB < Strategy
   methods
      function result = algorithm(obj, input)
         result = input / 2;
      end
   end
end
291 chars
16 lines
  1. Define a Context class that uses the Strategy classes to execute the algorithm. The Context class should have a set of methods that allow setting the active strategy dynamically.
main.m
classdef Context
   properties
      strategy
   end
   
   methods
      function obj = Context(strategy)
         if nargin > 0
            obj.strategy = strategy;
         end
      end
      
      function setResult(obj, input)
         result = obj.strategy.algorithm(input);
         fprintf('Result: %d\n', result);
      end
      
      function setStrategy(obj, strategy)
         obj.strategy = strategy;
      end
   end
end
439 chars
23 lines
  1. Create an instance of the Context class and initialize it with the desired Strategy class. Then, call the method that executes the algorithm.
main.m
context = Context(ConcreteStrategyA());
context.setResult(10); % Outputs: "Result: 20"

context.setStrategy(ConcreteStrategyB());
context.setResult(10); % Outputs: "Result: 5"
176 chars
6 lines

In this example, the Strategy Pattern is used to define two different algorithms (doubling and halving a number) and executing them dynamically based on the selected strategy.

related categories

gistlibby LogSnag