Sunday, December 7, 2014

Design Pattern : Strategy Design Pattern

Type Behavioral Design Pattern


Summary

It enables an algorithm's behavior to be selected at runtime.  Multiple Strategies exists and Client select one strategy at run time.

The strategy pattern,
defines a family of algorithms,
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.

Advantages

The strategy pattern uses composition instead of inheritance. In the strategy pattern, behaviors are defined as separate interfaces and specific classes that implement these interfaces.
It obeys  Open/Closed Principle which says Classes should be open for Extension but closed for modifications.

Simple Use Case

Consider the use case of online Advertisement i,e displaying of an advertise. We can consider different mediums of advertisement like TextAdd or video Adds or evan Image adds.

Class Diagram






Explanation 


Sample Code


Difference with State Pattern

Both State Pattern and Strategy Pattern looks same in UML. The difference are summarized bellow,

State Pattern encapsulate State of an Object, Strategy encapsulate Algorithms. States are more tightly coupled with Object.

In State Pattern, State Object may contain reference to Context to facilitate transitions between states, In Strategy Pattern does not contain reference to Context.


Change of Strategy is done by Client, but Change is State can be done by both Context or State itself.

No comments :

Post a Comment