File Exchange

image thumbnail

Strategy Design Pattern in Matlab 2008b

version 1.0.0.0 (2.68 KB) by Paul Williamson
Strategy Pattern defined by "Gang of Four" in: "Design Patterns: Elements of ...," Gamma, et al.

1 Download

Updated 20 Nov 2008

View License

The Strategy Pattern is just one of many patterns defined by the "Gang of Four" that are commonly used in many other object-oriented programming languages.

Now with Matlab 2008b we can define Interfaces and Abstract classes that can make use of many of these patterns. Not only is this good coding practice, but they make code much more reusable, easier to maintain and change over time. In addition they provide us with a common language to discuss various programming structures.

The GoF define the Strategy Pattern as: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

In this simple example we have time series data stored in a TimeSeries class (to keep it simple I have just given it a name property). Then, suppose that we have a number of technical indicators that we wish to use on this time series data, but we’re not told which one until runtime. In addition we need to be able to add new technical indicators easily in the future.

By using this structure we’re passing around the TimeSeries() class. By having an Abstract Strategy Interface we can add as many more technical indicators as we like. All we need to do is add to the switch statement in StrategyType class and implement the RunStrategy method in our new class which inherits from StrategyType.

Note also how easy it would be to completely change behaviour at runtime by setting a new Strategy in the Main.m.

Usage: Extract the separate files and type Main in the command window

Cite As

Paul Williamson (2020). Strategy Design Pattern in Matlab 2008b (https://www.mathworks.com/matlabcentral/fileexchange/22193-strategy-design-pattern-in-matlab-2008b), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Zaki

great addition

MATLAB Release Compatibility
Created with R2008b
Compatible with any release
Platform Compatibility
Windows macOS Linux