strategy pattern with function handles in matlab

The Strategy design pattern can be implemented in MATLAB using function handles. Here is an example of how to implement the Strategy pattern using function handles:

  1. Define the context class. This class will use the chosen strategy.
    main.m
    classdef Context
       properties
          strategy
       end
       
       methods
          function obj = Context(strategy)
             obj.strategy = strategy;
          end
          
          function result = executeStrategy(obj, input)
             result = obj.strategy(input);
          end
       end
    end
    
    270 chars
    16 lines
  2. Define the interface that the strategies should implement. This is not strictly necessary, since we are using function handles, but it is good practice to define an interface for the strategies so that they can be easily swapped out.
    main.m
    classdef (Abstract) Strategy
       methods (Abstract)
          result = execute(input)
       end
    end
    
    92 chars
    6 lines
  3. Define some concrete strategies. In this example, we define two strategies that implement simple operations on a scalar input.
    main.m
    function result = addTwo(input)
       result = input + 2;
    end
    
    function result = multiplyByTwo(input)
       result = input*2;
    end
    
    124 chars
    8 lines
  4. Create function handles for the strategies.
    main.m
    addTwoHandle = @addTwo;
    multiplyByTwoHandle = @multiplyByTwo;
    
    62 chars
    3 lines
  5. Use the strategies by creating a Context object and passing in the desired strategy function handle.
    main.m
    context = Context(addTwoHandle);
    result = context.executeStrategy(3); % Result should be 5
    
    context = Context(multiplyByTwoHandle);
    result = context.executeStrategy(3); % Result should be 6
    
    190 chars
    6 lines

This implementation allows for easy swapping of the strategies by simply passing in a different function handle to the Context constructor.

related categories

gistlibby LogSnag