Design Patterns Series: The Strategy Pattern

To use the example from Head First: Design Patterns, suppose you have a class called Duck and two classes that inherit it: MallardDuck and RedheadDuck.

Duck
quack()
swim()
display()
fly()

What happens when you are asked to implement a RubberDuck class? A RubberDuck does not fly() or quack() so the design is a bit off.  This is actually a great example that illustrates that a “has a” relationship is better than an “is a” relationship.  Instead of inheriting from a Duck superclass, we will be inheriting some interfaces, that represent behaviors – FlyBehavior and QuackBehavior.

The Strategy Pattern, as the book describes it is, “defines a family of algorithms, encapsulates each one, and makes them interchangeable.  Strategy lets the algorithm vary independently from clients that use it.”   Here is what the Duck class looks like after we apply the Strategy pattern.
Client

Duck
FlyBehavior flybehavior
QuackBehavior quackBehavior
swim()
display()
setFlyBehavior()
setQuackBehavior()

encapsulates

FlyBehavior (interface)
fly()

inherited by

FlyWithWings
fly()

and

FlyNoWay (used by RubberDuck)
fly()

Similarly, you can have apply the same principle to QuackBehavior.

Here is what the code looks like in C#.

public abstract class Duck
{
  QuackBehavior quackBehavior;
  FlyBehavior flyBehavior;
}
public class MallardDuck : Duck
{
   public MallardDuck()
   {
        flyBehavior = new FlyWithWings();
        quackBehavior = new Quack();
   }
}
public class RubberDuck : Duck
{
     flyBehavior = new FlyNoWay();
     quackBehavior = new QuackNoWay();
}

The takeaway here is to use behaviors, or has-a relationships on entities that might change later on so that you don’t have to rewrite the parts of the code or class that do not change.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>