Note: CLICK ON THE IMAGE TO ENLARGE IT.
About : A beautiful design pattern which demonstrates how we can ,through the use of composition( HAS-A relation) over inheritance( IS-A relation) , reduce the harmful effects of change in code and make the design more flexible.
We can change behavior at runtime and change the code without affecting the client, which uses them.
Definition : The strategy Pattern defines a family of algorithms, encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
When to use it: when we have common type of behavior in our various subclasses and they may change in future and if the subclasses are too many then we need to change the the behavior by editing each and every class where change is needed. This happens because our implementation is “locked” inside our subclasses and thus whenever change is required we need to change each and every subclass.
How to use it : Identify aspects of our application that vary and separate them from what stays the same. So, by making a loose coupled design through the interface we make the caller unaware of the implementation and thus implementation can change without touching code at the caller side.
Example : Lets say we have a class which has two behaviors one is common to both the subclasses and other is new behavior which is applicable to one subclass which not to the other. So in this case if we depend on inheritance then we have to give empty implementation of the new behavior in the SubClass2. This design is not loosely coupled, implementation is locked inside subclasses. So in case we have to change the new behavior in any subclasses then we need to make changes there. If there were 20 behaviors and 100 subclasses then the changes would be felt worst.
Lets improve the design a little bit. This time we'll separate the implementation not through inheritance but through composition.
Conclusion : Separate the functionalities of your application that changes from what stays the same. And prefer to use composition over inheritance when you need a flexible design because interface gives dynamic allocation of objects and loose coupling while inheritance gives implementation which is static inside the class and makes code hard to manage when exposed to changes.
Any suggestions or queries are welcomed.
No comments:
Post a Comment