« Back to blog
July 05, 2008

Hello(with Strategy Pattern)

This is my first post and official opening of the blog. In this very first post I will talk about  a design pattern called "Strategy Pattern".

In Gang Of Four(GoF)'s design pattern book it is defined as "Define a family of algorithms, encapsulate each one, and make them interchangeable. [The] Strategy [pattern] lets the algorithm vary independently from clients that use it."

The Strategy Pattern makes the the desired behavior of an object changeable at run time. It does this by encapsulating the behavior(algorithm) in a seperate class and giving a reference to this behaviour class to the object. Three important design principle applied here. "Encapsulate What Varies" , "Favor Composition Over Inheritance" and "Program To An Interface, Not Implementation".

I want to show how The Strategy Pattern works with an example. Suppose you design a game. Each character may use a weapon at a time and can change his/her weapon any time. It is obvious that the changing part of the problem is weapon behavior. So I should apply the design principle "Encapsulate What Varies" . I will create a new set of classes and encapsulate weapon behaviour in these classes. This set of classes will implement an interface called WeaponBehaviour. So I make use of the "Program To An Interface, Not Implementation" design principle. By doing this, I get a flexible design. The classes which implement WeaponBehaviour interface will be interchangeable.

For a minute think that I don't know The Strategy Pattern and I used inheritance to implement the solution. What will happen? I locked the behaviour to concrete classes and the behavior can not be changed at run time. This show the importance of the  "Favor Composition Over Inheritance" design principle. Instead of inheriting behaviour, Character class should get weapon behavior by being composed(holding e reference) with the right WeaponBehavior object. Another disadvantage of using inheritance, a bigger ang obvious one, when a behaviour is wanted to be added, all character classes are needed to be changed. On the contrary , adding a behavior is a piece of cake if The Strategy Pattern is applied. Because, adding another class which implements WeaponBehavior interface will be enough.

The resulting class diagram is below; 

The example is from "Head-First Design Patterns" book. They ask it as as a design puzzle. I find it appreciate to use in this post. Below I give a link about a real-world use of The Strategy Pattern in Swing.

http://www.javaworld.com/javaworld/jw-04-2002/jw-0426-designpatterns.html



Comments (0)
Leave a comment...
 
Got a posterous account already? Login