The very first chapter in the awesome Head First Design Patterns book explains 3 fundamental design principle that forms the basis of Strategy design pattern. These principles are
- Identify the aspect of your application that vary and separate them from what stays the same.
- Program to an interface, not an implementation.
- Favor composition over inheritance.
The example code in Chapter 1 Intro to Design Patterns provide Java Implementation of Duck Simulator. I tried to write similar code in C++ that explains the Strategy Pattern used in the program. The behaviors of a duck that can vary ( Fly Behavior, Quack Behavior ) are encapsulated as family of classes and the non varying part ie Duck Class is base class for different types of ducks ( principle 1). Duck acts as client and make use of encapsulated family of behaviors/algorithms. This particular design is Strategy pattern and it defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that uses it.
Here is the class diagram of SimUDuck simulator
The c++ code is build using VS2010 IDE. You can download code from here.
No comments:
Post a Comment