Design Patterns

Strategy



Design Pattern Type: Behavioral

GoF Statement of Intent:


Define a family of algorithms, encapsulate each one, and make them interchangeable.
Brief Overview:



Sometimes referred to as the Policy Pattern. It allows the selection of a particular algorithm to accomplish some task at run time. Which implies that the current state of the object can determine which algorithm it uses and allow it to dynamically change that algorithm at run time. This is most easily accomplished by separating the algorithms into a separate classes from the object and having a reference (pointer) to the appropriate algorithm. If all the algorithm classes are subclasses of the same parent then the object can contain a pointer to the parent class and set it pointing to any of the subclass algorithm implementations.
UML Diagram:

Discussion and In-class Example:

In the Strategy Design Pattern we used the example of the Sim-U-Duck application in which we were instantiating instances of subclasses of Duck. But each time we added a new type of Duck we had to change the code in the superclass, which meant we would have to also modify all the subclasses.

By isolating and encapsulating those behaviors which changed (flying and quacking in this example) we created a Duck class that contained a FlyBehavior and a QuackBehavior. The actual behavior was delegated to the Families of Algorithms (FlyBehavior and QuackBehavior). This way we could assign the appropriate behaviors at run time instead of compile time. And, it meant that it was very easy to add new behavior to a Duck without changing the code in the Duck class or its subclasses just by adding new subclasses of the behaviors.

It is easy to see how we could have also done the same with the swim behavior and even with the display function.