«

»

Jan 14

Print this Post

Design patterns: strategy

I became a little bit lazier at the end of previous year. Of course in terms of taking care of this blog ;) But, new year has come! And as it usually is new goals are slowly being visible on the horizon. One of those goals for me will be getting more familiar with software design patterns. I have been programming, creating lines of code for a quite long now and probably once or few more times I used a design pattern. But what I would like to achieve is to think and be able to talk to others in a specific way — design pattern’s way ;)

I thought about it earlier. I even bought myself really interesting book recommended to me by many others: Head First. Design Patterns. I read some of the chapters but not all. And the book has been lain untouched on my bookshelf for a little bit more than a year now. So, an idea has come to my head with the goal I would like to achieve this year: I will be describing here a design pattern from the book each month. This month I would present the strategy design pattern.

Book examples

There are “only” two examples in the book and both are written in Java (as all other examples in this book). The first one is funny and describes a duck simulator ;) At the beginning we are presented with standard object-oriented code with inheritance used:

class Duck {
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function swim() {
    //swimming implementation
  }
  public function display() {
    echo 'Duck.';
  }
}

class MallardDuck extends Duck {
  public function display() {
    echo 'Mallard duck!';
  }
}

class RedheadDuck extends Duck {
  public function display() {
    echo 'Redhead duck.';
  }
}

Pretty simple — as the new requirement presented on next pages of the book: “we would like to add flying ducks to our application”. The first idea which came to the mind was to add fly() method to our base class Duck.

But it was not as good idea as it supposed to be: probably another developer added RubberDuck sub-class to the simulator and it started “to fly”. And it was not well-received during demo of the application. We could stop here and think about what if there are other types of ducks which do not fly or event do not quack? Keeping in mind that we need overwrite their fly() and/or quack() methods does not sound as the best way to use our time.

Another doubtful idea is to use interfaces:

interface IFlying {
  public function fly();
}

interface IQuacking {
  public function quack();
}

class Duck {
  public function swim() {
    //swimming implementation
  }
  public function display() {
    echo 'Duck.';
  }
}

class MallardDuck extends Duck implements IFlying, IQuacking {
  public function fly() {
    //flying implementation
  }
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function display() {
    echo 'Mallard duck!';
  }
}

class RedheadDuck extends Duck implements IFlying, IQuacking {
  public function fly() {
    //flying implementation
  }
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function display() {
    echo 'Redhead duck.';
  }
}

class RubberDuck extends Duck implements IQuacking {
  public function quack() {
    echo 'Squeak! Squeak!';
  }
  public function display() {
    echo 'Yellow, rubber duck.';
  }
}

class DecoyDuck extends Duck {
  public function display() {
    echo 'Wooden decoy duck.';
  }
}

What is wrong with this example (it seems quite logic, doesn’t it)? Well, the duplication of code is something we should always avoid (quack() methods in alive ducks’ classes). Also, the time spend on introducing new sub-class is even longer than overwriting two methods. After this funny example we are introduced with strategy design pattern. I used here some kind of UML-like diagram instead of putting more code. However, I re-written the code from Java to PHP and you can download and run in a terminal.

strategy pattern diagram

Strategy design pattern diagram from “Head First. Design Patterns.” book

The second example in the book is an exercise just to remember better the strategy pattern. The reader sees different parts of a diagram and is asked to put them in order. There are:

  • Character base class,
  • King, Qeen, Knight, Troll sub-classes,
  • WeaponBehavior interface,
  • KnifeBehavior, SwordBehavior, AxeBehavior, BowAndArrowBehavior classes.

She is also asked to put this method into right class:

public function setWeapon(WeaponBehavior $w) {
  this.weapon = $w;
}

I will not put the solution here just in-case if anyone would like to solve it ;) But this is the second example in the book of use of strategy pattern.

Other examples

The examples in the book do not have much in common with web development, do they? So, once I have made my mind to write this post I checked Internet if there are any good examples. Of course, there are plenty of them. But the top of searching results, I found, were about different ways of displaying a book title, finding a transportation way or encapsulating different database algorithms.

Definition

At the end, just as in the book, I will just put definition of strategy pattern:

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Head First. Design Patterns.

Also, you can use Wikipedia to find another definition but it does not vary much. Actually in English Wikipedia the definition is from the book I mentioned hundreds times in this post ;)

Permanent link to this article: https://blog.lukaszewski.it/2013/01/14/design-patterns-strategy/

1 comment

  1. mheki

    W tematyce wzorców projektowych w PHP polecam książkę, którą czytałem: PHP. Obiekty, wzorce, narzędzia. Wydanie III Matta Zandstry – dużo przykładów wzorców i interesujące poboczne tematy. Zajrzyj jak będziesz miał czas.
    Pozdrawiam

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>