Friday, 19 June 2015

Strategy Design Pattern

Strategy beneath Strategy Design Pattern ??

It defines a family of behaviors, encapsulate each of them, and clients can modify their behavioral implementations dynamically without interchanging the behavior in abstract client family.

How behavior is different from clients:

A simple example where one behavior eat is similar in all clients of Animal class. But an animal can choose from behavior of an herbivorous or carnivorous or an omnivorous diets. These behaviors could be modified dynamically.

Super Class Sub-Classes IDietBehavior Dietary Behavior
Animal Bird eat Herbivorous
Cow Carnivorous
Tiger Omnivorous
PolarBear

Please try yourself with above classes, after understanding the below bank example.

Client behaviors can also vary independently without worrying about internal implementations.
Why do we need this pattern ?
  1. Reduces long list of conditional behavior.
  2. Avoid redundant code.
  3. Independent clients and behavior to disallow other classes to force change the current behavior.
  4. Encapsulation to hide code from user.


AbstractBank.java
HsbcBank.java
AxisBank.java
ILoanProvider.java
BlockMortgage.java
Mortgage.java
Test.java

Drawbacks : Increased number of classes, managing the code is also a little difficult.

No comments:

Post a Comment