Strategy design pattern
Strategy design pattern comes under behavioral design pattern. It create different strategy classes which is interdependent to the Parent class, and these classes can be used interchangeably in side the family of parent class.
Remember Always we should focus on future requirement and based on that we should design our application.
Book Definition
Problem
Lets say We have a video game where different kind of ducks do the different kind of operation.
Now Initially We have one abstract class called DUCK and one child class called ReadHeadedDuck. So we implemented inheritance concept and easily we achieve the functionality by reuse the code.
Its very easy right!! But there is some problem in it. we will discuss this below.
Now the game was more popular. So the owner of the video game thinking to add news features!!!!!!!
Now he added another object called RubberDuck.
Remember RubberDuck do not have all the functionality what ReadheadedDuck have. Then you need to forcefully implement the methods of DUCK in the RubberDuck even though its not required as it inheriting from parent DUCK.
This violates DRY Principle.
See the below code.
{
public abstract void Swim();
public abstract void Display();
public abstract void FlyBird();
public abstract void QuarkBird();
}
public class RedHeadedDuck : Duck
{
public override void Display()
{
//Implement Display functionality
}
public override void FlyBird()
{
//Implement Fly functionality
}
public override void QuarkBird()
{
//Implement Quack functionality
}
public override void Swim()
{
//Swim functionality
}
}
public class RubberDuck : Duck
{
public override void Display()
{
//Implement Display functionality
}
public override void FlyBird()
{
//Do not have Fly functionality
}
public override void QuarkBird()
{
//Do not have Quack functionality
}
public override void Swim()
{
//Implement Swim functionality
}
}
Lets say in future one more duck object will be added then we need
to implement some method forcefully which is very difficult to
maintain.
Solution
We should create a decoupled system which will help us to write less code and easy maintenance.
What should we do and how can we change the above code???
Step-1 Find the methods which can not be applicable to all the Objects(QuackBird() and FlyBird())
Step-2 Take those methods (Flybird(), Quackbird())and create a separate class called strategy class.
Step-3 Those strategy classes are used by the required objects of DUCK family.
See the below design as described in the above 3 steps.
Things to Remember
- Strategy Design Pattern helps to create strategy class.
- The Parent class not aware of the logic of the strategy class even though its part of the Parent class
- Strategy class can be implemented to the family of parent class based upon the requirement.
- Strategy design pattern is of behavioral type.
No comments:
Post a Comment