CSC/ECE 517 Fall 2010/ch3 3h ss
The Strategy Pattern
The Strategy pattern is a common design pattern that defines algorithms into familial groupings. It encapsulates the individual algorithms and makes those algorithms interchangeable. Strategy allows the algorithms to differ autonomously from the clients that use them.1 Here we will compare how the Strategy pattern can be implemented in static and dynamic languages, and then explore if Ruby has an advantage with this design pattern because of its dynamic nature or because of the features of Ruby.
Static Languages
The use of the Strategy design pattern in static languages requires the relations between classes and interfaces to be referenced by extending classes, implementing interfaces, instantiating objects, invoking methods, etc.2 The code in the hyperlinks below show various languages implementing the Strategy design patterns.
Java
Java Strategy design pattern example. This code identifies an interface for the related algorithms and shows the use of classes to implement the individual algorithms.4
C++
C++ Strategy design pattern example. This code uses a base class as the interface and "subclasses" to implement the individual algorithms.4
PHP
PHP Strategy design pattern example. This code uses a context class that will identify the strategy based upon a parameter.4
Dynamic Languages
The use of the Strategy design pattern in dynamic languages requires a variable that has a function as the value. Separate classes are not needed in dynamic languages. (3)
References
(1) Head First Design Patterns Freeman & Freeman
(2) OBJECTED-ORIENTED DESIGN PATTERN DETECTION USING STATIC AND DYNAMIC ANALYSIS IN JAVA SOFTWARE