An example implementation of the Strategy design pattern in C++

A mate put me on to the book Head First Design Patterns the other day, and it’s excellent, so I’ve been reading away and coding up the examples. The examples themselves are in Java, but I’m more interested in C++ so I’m transcoding them as I go (pun!).

The Strategy pattern aims to give separate implementations of algorithms (in other words – functions) to different subclasses of your major class, and allow you to change the behaviour at run-time, rather than have it hard-coded at compile-time. Pretty neat.

Now for the ducks…

Which gives the output:

I’m a real mallard duck!
The duck bobs peacefully on the surface of the water.
The duck flies into the friendly skies!
The duck says: Quack!

I’m a rubber-ducky!
The duck bobs peacefully on the surface of the water.
I can’t fly!
The duck says: <<< Silence >>>

I’m a painted wooden duck!
The duck bobs peacefully on the surface of the water.
I can’t fly!
Changing fly behaviour…
The duck flies through the air using a rocket!
The duck says: <<< Silence >>>
Changing quack behaviour…
The duck says: Quack!

Update 24th Nov 2012: ijab points out in the comments below that this code contains memory leaks, and yup it does – so I’ve provided a version with the memory leaks fixed in my reply below, but have deliberately left the original version above to keep things focused. All you really need to do avoid leaking memory is:
– Have virtual destructors for the xxxBehaviour classes (they don’t have to do anything special, but they need to exist or the compiler will give you warnings),
– Delete the existing behaviour before creating and applying a new one (maybe only delete if they’re not null – you choose), and
– Don’t forget to delete your ducks at the end of the program!

12 thoughts on “An example implementation of the Strategy design pattern in C++”

  1. Nicely done.

    Don’t know if you’ve already linked this, but a good condensed explanatory resource can be seen here.

    It’s got semantic class structures as well as example class structure diagrams, yo!

    1. Thanks, man. Nope – hadn’t seen that page before, looks like a great resource, and the semantic class structures are tiiiiiiiiiight! =P

  2. Memory leak in your codes. You new Behanvior objects in two Duck’s children class constructor, but not release them.

    MallardDuck()
    {
    quackBehaviour = new Quack();
    flyBehaviour = new FlyWithWings();
    }

    and

    RubberDuck()
    {
    quackBehaviour = new MuteQuack();
    flyBehaviour = new FlyNoWay();
    }

    1. Yup, you’re absolutely right. Running valgrind on the code as it stands gives:

      Memcheck, a memory error detector
      Copyright (C) 2002-2011, and GNU GPL’d, by Julian Seward et al.
      Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
      Command: ./5\ -\ Programming\ to\ an\ Interface

      HEAP SUMMARY:
      in use at exit: 136 bytes in 11 blocks
      total heap usage: 11 allocs, 0 frees, 136 bytes allocated

      LEAK SUMMARY:
      definitely lost: 88 bytes in 5 blocks
      indirectly lost: 48 bytes in 6 blocks
      possibly lost: 0 bytes in 0 blocks
      still reachable: 0 bytes in 0 blocks
      suppressed: 0 bytes in 0 blocks
      Rerun with –leak-check=full to see details of leaked memory

      This is both because we’re not deleting any existing behaviours before creating new ones, and because we don’t delete the ducks at the end.

      So to fix this, we could use code like this (changes are marked in comments with NEW tag):

      Running valgrind on that gives:

      Memcheck, a memory error detector
      Copyright (C) 2002-2011, and GNU GPL’d, by Julian Seward et al.
      Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
      Command: ./5\ -\ Programming\ to\ an\ Interface

      HEAP SUMMARY:
      in use at exit: 0 bytes in 0 blocks
      total heap usage: 11 allocs, 11 frees, 136 bytes allocated

      All heap blocks were freed — no leaks are possible

      I think that’s the correct way to eliminate the memory leaks, and there’s no compiler warnings about undefined behavior or anything – let me know if you’ve got a better way!

      Cheers!

    1. Glad you found it of use!

      And yes, I think you’re right – as we have a destructor we should probably have overloaded copy and assignment operators as well so that we can perform ‘deep copies’ of objects. However, in this example we don’t actually perform any assignment of one Duck object to another, or any duplication of Duck objects, so I didn’t provide these overloaded methods to keep things clean.

      I’m always interested in coding principles like this so if you find any other related / interesting things in your travels I’d love to hear about ’em =D

Leave a Reply

Your email address will not be published.