Design Patterns 101 – Strategy Pattern

Over the next few weeks, I'm going to use this space one day each week to go back to basics because – unfortunately – I discovered that many people don't have these basics.

A few weeks ago when I was digging up information on IBM's various PHP efforts, I found a great article "Five commmon PHP Design Patterns". If you're not from an Object Oriented background or haven't run into Design Pattern yet, the concept is quite simple:

a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Source: Wikipedia Design Pattern

Design patterns are not new. In fact, the concepts behind them go back 20+ years but it's really in the past 4-5 years that they've really gained prominence in software development in general. Unfortunately, although every PHP book mentions how to implement a basic Singleton Pattern – eg. for a database connection – they miss one of my favorites which happens to be one of the foundations of Object Oriented Programming… the Strategy Pattern.

Strategy Pattern

The Strategy Pattern is the starting point of interfaces which serve as a convenient way of working with multiple different types of objects in a similar fashion even though the actions happen differently. Let's dive into a simple example:

Let's say you had two types of objects – like a Project and a Task – which you need to be able to do save it to a database. Despite the fact that the objects are different and the underlying implementations are completely different, it becomes quite useful to interact with them identically. In real terms, instead of having to use:

$task->saveTask(); or $project->saveProject();

you can use:

$task->save(); or $project->save();

At first glance, this only saves us a few keystrokes and seems relatively pointless…. but stop and look again. When you can interact with your objects in identical ways, your code gets much simpler. Let's rewrite it like this:

$object->save();

and it becomes even more clear. We don't care what the object is, we don't care how the save() is done, in fact, we don't even care that it is done. As long as it doesn't error and returns a value we're expecting, the operation is fine. The only thing we care about is that the objects can be treated exactly the same which we enforce by writing Interfaces.

Obviously this can be applied to your various objects, but it doesn't take much to consider how to apply this to connecting to different databases, or even interacting with files over a network connection versus a local filesystem.

So where does this make sense in your applicaiton?

The image used above is from the "Design Pattern improvement catalog for MixJuice".