Design Pattern Chronicles 1 — The Strategy Pattern

Long story short

Strategy pattern enables an algorithm’s behavior to be selected at run time by putting them in composition instead of concrete implementation

Long story

We have two sub classes Skateboard and a Surfboard for the super class Board as a result of Generalization. We have a method ride() which implements the tricks which a rider can perform in its subclass.

Now we add one more class — Let’s suppose there comes a Flyingboard in future, which can make you fly in the sky using its jet engines and wings.

What are the problems with above design?

The ride() method which we are overriding in current design has to be implemented (and/or copy pasted) for each subclass . The skateboard is for land, surfboard for water and flying board in air.

What if a type of board in future doesn’t perform ride() move? It still inherits the ride() behavior from super class. Although we can override ride() to do nothing in that case but you may have to do so for many existing classes and take care of that for future classes too. This would also make maintenance difficult. So we can’t use inheritance here.

What about an Interface?

Take a look at the following design:

It’s much cleaner. We took out some action (which some characters might not perform) out of Board class and made interface for them. That way only boards that are supposed to ride will implement the Ride Behavior.

What are the problems with above design?

The main problem with the above design is code reuse. Since there is no default implementation of ride and fly behavior we may have code duplicity. You may have to rewrite the same ride behavior over and over in many sub classes.

How can we avoid this?

What if we made RideBehavior and FlyBehavior classes instead of interface? Well then we would have to use multiple inheritances that are not supported in many languages due to many problems associated with it.

Here strategy pattern comes to our rescue. We will learn what the strategy pattern is and then apply it to solve our problem.

Definition:

Wikipedia defines strategy pattern as:

“In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm’s behavior to be selected at runtime. The strategy pattern

defines a family of algorithms,

encapsulates each algorithm, and

makes the algorithms interchangeable within that family.”

The Strategy Pattern:

Find out the behaviors that may vary across different classes in future and separate them from rest. In our example the ride and flying behaviors will have new set of classes to represent each behavior.

The Board class will now delegate its riding and flying behavior instead of using ride () and fly () methods defined in Board class or its subclass