What?The strategy pattern is a design pattern designed to accommodate situations when there are multiple ways of doing some/similar thing(s). For instance this might be something along the lines of, if you are designing a media player - you would have different algorithms for playing the different media types. You could use the strategy pattern, as it deals with a common problem of playing a media file, except there are multiple ways it could be done (which algorithm depends on the media type).
How?Each strategy is made into its own class, in our example above they may be classes like:
Class PlayWAV;
Class PlayMP3;
Each of the above class would implement the IStrategy interface (defined below):
Interface IStrategy {
// This is the function that is called to execute this strategy
public function execute();
}
A pseudo-code (may look similar to PHP code) implementation would look like this:
class PlayWAV implements IStrategy {
// Constructor: Information needed to execute the strategy may be passed through the constructor
public function PlayWAV(File fileObject);
// This needs to be implemented to satisfy the interface; this is the function that would be called to execute the strategy
public function execute();
}
class Context {
public function main() {
...
if (filetype(...) == "WAV") {
$strategyA = new PlayWAV(...);
$strategyA->execute();
} else {
$strategyB = new PlayMP3(...);
$strategyB->execute();
}
...
}
}
Why?
Why the heck would you do this? and not just code everything using an if/else? Well, this provides a clean separation - each strategy is its own entity - this reduces any tight coupling that may be formed knowingly or unknowingly. Since this is build with loose-coupling, you can change each without worrying about affecting the other, and new strategies may be developed independent of the application code and be integrated into the application with ease.
ExampleThis whole post was explained using an example, another great one can be
found here. This one uses the strategy pattern for form validation in PHP.
And now with that I will end this post. Ciao.
Labels: patterns