This is the first post for me in the field of Design Patterns. I am new to this field, but decided to summarize each pattern I cover in my great book called: Head First Design Patterns.
The Strategy Pattern:
Defines a family of algorithms, encapsulates each one, and makes them interchangable. Strategy let the algorithm vary independently from clients that use it.
The idea is as follows: Suppose you are developing a game where you will have different players or characters. Each character can make use of one Weapon at a time, but can change the weapon at any time during the game.
We have several characters in the game, we think directly of having a base Character object, and each character can inherit from that base class.
Now, as mentioned, each character needs to use a weapon, which is nothing but a behaviour, but also wants to be able to change that weapon at run time. We might have different kinds of Weapons. Every weapon has a behaviour, so you might think of having an Interface called Weapon and all the behaviours of that Weapon will be represented by algorithms or objects implementing that interface, each having its own implementation of the Weapon, hence each having its own algorithm.
So the base class we had before, now has its own behaviour implemented by the family of algorithms that implement the Weapon Interface.
This way, any object inheriting from the base Character class, can use any Weapon implementation, and can change from one Weapon to another at run time, but means of an inherited member placed in the base Character class of type Weapon Interface.
So when you have several objects that are basically the same but only differ in their behaviours. It is better to use the Strategy pattern, in which you seperate the objects from their behaviour, making the addition of new behaviours easy, and then alalowing those objects to change any behaviour at run time and hence getting rid of the subclassing method to provide common behaviour to the objects.
Hope this helps,
Regards
Tags: Design Patterns