CSC/ECE 517 Fall 2007/wiki1b 8 ktrk
Introduction
What is the Strategy Pattern?
The strategy pattern is a proven object oriented design pattern that can be used to solve a common coupling problem often found in software development. Often during the development of compositional classes, behaviors and algorithms can become mixed into the class during development without realizing that these behaviors or algorithms may change, become more complex, or additional behaviors may need to be added. These changes could be implemented by extending the class's behavior through inheritance, but over time this could result in an overly complex class hierarchy. The strategy pattern is a design template that can be used to decouple the behavior and algorithms from the object being acted upon.
Generic Strategy Class Diagram
When to Use the Strategy Pattern
In the seminal book on design patterns by the Gang-of-Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides), situations (also labeled "code smells" by Martin Fowler in Refactoring) are described where the strategy design pattern could be used to architect a better solution. These include:
- A class that exhibits many behaviors
- A class that uses many variations of an algorithm
- A class that uses data structures related to a behavior but not the class
- Many similar classes that differ only in a type of behavior
Advantages of the Strategy Pattern
By decoupling through the use of composition rather than inheritance, several advantages emerge that improve the maintainability and readability of the code.
- Allows classes to change behavior at runtime or design time
- Decreases code duplication among classes using variations of the same behavior [1]
- Behavior is better encapsulated by not being buried in its context [2]
- A well known design pattern communicates the intent of the code more readily
Similar Patterns
Use the state pattern when the state of the object changes with a change in behavior.
Use the bridge pattern when a structural design is needed.
Use the command pattern when the invoking object (the context object in the state pattern) does not have knowlege of the recipient object (the behavior in the state pattern). The intermediary command object takes care of dispatching the request to the appropriate object.
For a discussion of the strategy pattern compared to the state and bridge patterns see Strategy Pattern vs. Bridge Pattern.
Strategy Pattern Implementation in Java and Ruby
For our example, we chose to model a video game where there could be different types of Fighters pitted against each other, as you might see in the UFC. In our case, the strategy is the Attack. Each Fighter has a different type of Attack according to his training. The Fighter is therefore an "abstract" class. In statically-typed Java, the class itself is declared as abstract, and in dynamic Ruby it must be extended (or else the Fighter will not know any techniques). To keep things simple, our fighters are not very smart or well-trained, so they each only get one Attack. To see our Fighters in action, there is also a Fight class in Java, and a Fight script which can be run in Ruby.
Class Diagram
Java
Fighter.java:
package csc517.wiki1b; public abstract class Fighter { private Attack attack; public Fighter(){ setAttack(); } public Attack getAttack() { return attack; } public void setAttack(Attack attack) { this.attack = attack; } protected abstract void setAttack(); public void fight() { getAttack().execute(); } }
JudoPlayer.java:
package csc517.wiki1b; public class JudoPlayer extends Fighter { public void setAttack() { setAttack(new LegSweep()); } }
KickBoxer.java:
package csc517.wiki1b; public class KickBoxer extends Fighter { public void setAttack() { setAttack(new RoundhouseKick()); } }
Boxer.java:
package csc517.wiki1b; public class Boxer extends Fighter { public void setAttack() { setAttack(new Jab()); } }
Wrestler.java:
package csc517.wiki1b; public class Wrestler extends Fighter { public void setAttack() { setAttack(new ShootIn()); } }
Attack.java:
package csc517.wiki1b; public interface Attack { public void execute(); }
RoundhouseKick.java:
package csc517.wiki1b; public class RoundhouseKick implements Attack { public void execute() { System.out.println("Roundhouse Kick!"); } }
ShootIn.java:
package csc517.wiki1b; public class ShootIn implements Attack { public void execute() { System.out.println("Shoot In!"); } }
LegSweep.java:
package csc517.wiki1b; public class LegSweep implements Attack { public void execute() { System.out.println("Leg Sweep!"); } }
Jab.java:
package csc517.wiki1b; public class Jab implements Attack { public void execute() { System.out.println("Jab!"); } }
Fight.java:
package csc517.wiki1b; public class Fight { public static void main(String[] args) { Fighter[] fighters = { new Boxer(), new Wrestler() }; for (int round = 0; round < 3; round++) { for (int fighter = 0; fighter < fighters.length; fighter++) { fighters[fighter].fight(); } } } }
Ruby
Fighter.rb:
class Fighter attr_accessor :attack def initialize(technique) @attack = technique end def fight @attack.execute end end
MethodMissing.rb
module MissingMethod def method_missing(method_name) puts "I don't know how to #{method_name}" end end
JudoPlayer.rb:
require 'Fighter' class JudoPlayer < Fighter def initialize(technique) super(technique) end end
KickBoxer.rb:
require 'Fighter' class KickBoxer < Fighter def initialize(technique) super(technique) end end
Boxer.rb:
require 'Fighter' class Boxer < Fighter def initialize(technique) super(jab) end end
Wrestler.rb:
require 'Fighter' class Wrestler < Fighter def initialize(technique) super(shoot_in) end end
RoundhouseKick.rb:
require 'MethodMissing' class RoundhouseKick include MethodMissing def execute puts "Roundhouse Kick!" end end
ShootIn.rb:
require 'MethodMissing' class ShootIn include MethodMissing def execute puts "Shoot In!" end end
LegSweep.rb:
require 'MethodMissing' class LegSweep include MethodMissing def execute puts "Leg Sweep!" end end
Jab.rb:
require 'MethodMissing' class Jab include MethodMissing def execute puts "Jab!" end end
Fight.rb:
# Create two fighters assigning initial attack types rounds = 3 fighters = [ JudoPlayer.new(LegSweep.new), KickBoxer.new(RoundhouseKick.new) ] # Fight three rounds rounds.times do fighters.each do |fighter| fighter.fight end end # now swap in new behaviors fighters[0].attack = ShootIn.new fighters[1].attack = Jab.new fighters.each do |fighter| fighter.fight end
Comparison of Implementations
Clarity
Both languages can do the basic implementation of the design pattern framework with near equal clarity. The Java implementation relies less on language idioms, making it somewhat more clear (but not always). For example, to anyone familiar with O-O languages (but not necessarily Java), it is clear what each of the concrete Fighter types does, as well as the Attacks. However, the abstract Fighter class might not be as obvious (but probably still should be). Once the framework of the design is in place, there are many features of the Ruby language that could be used to make the implementation more succinct than than the Java version.
Succinctness
Overall, the two implementations are fairly similar in their succinctness, but in general, the Ruby implementation is more concise. Ruby's built-in iterators make it easier to work with collections, like arrays of Fighters, or rounds in a Fight. Also, the Ruby version contains fewer lines of code than the Java implementation. If you ignore packaging (Java package statements) though, there are actually more lines in the Ruby implementation. However, Ruby does offer a means to further simplify the code by using its block construct and Proc objects. This will work for simple strategy patterns and could allow for the elimination of the behavioral classes altogether. To make a comparison with Java, the Java strategy pattern would need to be implemented using anonymous inner classes, in which case Ruby's more versatile block construct would be easier to implement and maintain.
The real advantage to using Ruby becomes more apparent when you extend the design to model more real-world situations. Then you can take advantage of its dynamic nature. For example, let's consider when a Fighter wants to learn new techniques, and be able to choose which one to use. In Java, you need to create new Attack implementations before you can use them in a Fight. Then you need to create a mechanism to choose which attack to use. The block idiom in Ruby would allow new attack behaviors to be created on the fly at run time in addition to being assigned at compile time. This meta-programming capability allows flexibility that Java does not support. Also, if you wanted to combine several attacks into an arsenal from which the fighter could choose any attack, this could be easily accomplished using Ruby's arrays and built-in iterators.
Concluding Remarks
It would be nice to be able to say that one implementation was always clearer or more succinct than the other, but as with most things, it is a compromise. To get a little more clarity in Java, you sacrifice some succinctness, and in Ruby you can get more succinctness for the price of some clarity. Choosing a design implementation may come down to familiarity with the language or design decisions outside the scope of this discussion.
References
Design Patterns, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Addison-Wesley Pulishing, 1995
Refactoring: Improving the Design of Existing Code, Martin Fowler, Addison-Wesley Publishing, 1999
Head First Design Patterns, Eric Freeman and Elisabeth Freeman with Kathy Sierra and Bert Bates, O'Reilly Media, 2004
Programming Ruby, Dave Thomas with Chad Fowler and Andy Hunt, The Pragmatic Programmers, 2005
CSC/ECE517 Lecture Notes (lecture 10), Edward F. Gehringer, 2007
Command vs Strategy Pattern? (OO, Patterns, UML and Refactoring forum at JavaRanch)
Rubynoob Strategy Design Pattern in Ruby
Re: Head First Design Patterns - Strategy Pattern [was: Java/C# "interface" in Ruby ?]