Strategy Pattern

This will be my first article about design patterns.I planned to mention the Strategy Pattern. At the moment, i am reading a design patterns book which is Head First Design Patterns of O'Reilly and following it and sourcemaking web site.

The main purpose of all design patterns is no modification and limitless extension as mention in the book. Strategy Pattern is for non-duplicating code, reusability and modularity. I don't tell so deep knowledge as book, just write some hints and when / where the pattern is used. The book tells this pattern with a Duck sample that is pretty comprehensible, step by step while showing our fault. There are a base class called Duck and some inherited classes from it such as MallardDuck and eadheadDuck.
The base class has quack, swim, display, fly functions at the beginning. There is no problem until here but the programmer wants to add rubber duck to among inherited classes. Thus, fly and quack functions don't run for rubber ducks :) The programmer separates fly and quack function as interface, makes them Flyable and Quackable interface. So, flyable and quackable ducks can extend Flyable and Quackable interface but there is extra work. If the class wants to inherit from Duck class have to extend these interface. For this problem, first advise ;

"Identify aspect of your application that vary and separate them from what stays the same."

The programmer changes Flyable and Quackable interfaces to FlyingBehaviours and QuackingBehaviours interface, then creates some concreate classes from these interfaces, FlyWithWings and FlyNoWay from FlyBehaviour which has fly function (pure virtual in cpp), Quack, Squeak and MuteQuack from QuackBehaviour which has quack function (pure virtual in cpp). These base interfaces reference (or pointers and protected keyword is available in cpp) are stored in and two functions called performQuack and performFly are added to Duck class. Each inherited class can fix its properties via these references. Mallard duck can quack and fly with wings, rubber duck can squeak and not fly etc. The last class diagram is following :



In conclusion, the message of this pattern is "Favor composition over inheritance." :)

https://github.com/borcun/free/tree/master/cpp/DesignPatterns/Strategy%20Pattern

Popular posts from this blog

Polya’nın Problem Çözme Teknikleri

Mikroislemci Temelleri