CSC/ECE 517 Fall 2010/ch3 3h ss

From Expertiza_Wiki
Revision as of 01:31, 7 October 2010 by Srstarr (talk | contribs)
Jump to navigation Jump to search

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 an input 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 Each version of the algorithm is implemented as a different object which is then varied by supplying alternative strategy objects to the context.5

Ruby

class Context

 def initialize(&strategy)
   @strategy = strategy
 end

 def execute
   @strategy.call
 end

end

a = Context.new { puts 'One strategy for the context' } a.execute

b = Context.new { puts 'Another strategy for the context' } b.execute

c = Context.new { puts 'An additional strategy for the context' } c.execute



References

(1) Head First Design Patterns Freeman & Freeman

(2) OBJECTED-ORIENTED DESIGN PATTERN DETECTION USING STATIC AND DYNAMIC ANALYSIS IN JAVA SOFTWARE

(3) Design Patterns in Dynamic Programming

(4) Strategy Design Patterns

(5) Design Patterns in Ruby Olsen