Strategy Design Pattern
Author : Milan D Ashara
Programming is a very easy task, but to write code that
is maintainable needs experience and knowledge of design patterns. Design
patterns are knowledge of well known coding style(writing maintainable code) for
solving a particular type of problem. The important part is not learning design
patterns but to indentify areas in application where design patterns can
be applied.
I am going to write about simple "Strategy design
pattern" one among the various design patterns.
Identify which behaviour of the class/algorithm you are writing varies at
run time. These behaviour should be the instance of the class. In our example Context
class has behaviour ConcreteStrategyA and ConcreteStrategyB. These behaviour
can be changed at run time by using setter method. The code of above image looks
like this
//Strategy
Interface
public
interface
Strategy
{
public
void
execute();
}
public
class
ConcreteStrategyA
implements
Strategy
{
public
void
execute()
{
//execute
}
}
Where it can be used..
The Strategy pattern is to be used where you want to choose the
algorithm/behaviour/strategy(anything that varies at runtime) to use at runtime.
A good use of the Strategy pattern would be saving files in different formats,
running various sorting algorithms, or file compression.
The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.
The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.
knowing design pattern is not enough. Finding areas in application where it
can be applied is important.
Real World Senerio were it can be used :
Imagine a shopkeeper selling many items at his post. There are so many customer who buys different items.
Here different item are different behaviours that varies.
Shopkeeper is the our context class who has to decided at run time which customer buys which item and accordingly to that shopkeepe generate invoice for that customer.
Invoice invoice=context.generateInvoice(item);
Invoice is generated accordingly to the type of item is passed to generateInvoice method.
Real World Senerio were it can be used :
Imagine a shopkeeper selling many items at his post. There are so many customer who buys different items.
Here different item are different behaviours that varies.
Shopkeeper is the our context class who has to decided at run time which customer buys which item and accordingly to that shopkeepe generate invoice for that customer.
Invoice invoice=context.generateInvoice(item);
Invoice is generated accordingly to the type of item is passed to generateInvoice method.
OO Principles covered in Strategy Design Patterns are
1. What varies should be encapsulated
2. Prefer composition over inheritance : U
3. Program to interfaces not to implementation
It is simple design patterns widely used.