Strategy Design Pattern (aka Policy Pattern)

The strategy pattern is a behavioral pattern that defines a family of algorithms, encapsulates each one of them and makes them interchangeable. According to this pattern, a different class is created for each interchangeable algorithm, and this class can be injected anytime, even at runtime.  

 

Components and working of Strategy Pattern

Important components of strategy pattern are:

  1. Strategy interface, which declares the abstract strategy method.

  2. Concrete Strategy Class, that provides implementation for the Strategy

  3. Context Class, that has a reference to the Strategy interface, will be provided with a concrete implementation of the Strategy at runtime and will delegate the strategy behavior call to the provided implementation.

The base class can be called the context class. All the related behavior classes will have a common interface (or abstract class), which has a method declared for this algorithm. This is the Strategy interface. There will be a reference type of this abstract parent as a member variable in the context class and we can inject the right behavior class implementation (Concrete Strategy) based on the algorithm required, even at runtime. The context class receive requests and delegates it to the injected strategy object. Strategy design pattern is also called Policy pattern.

 

Summary of steps to use Strategy Pattern

Steps to use strategy pattern can be summarized as:

  1. Identify an algorithm that may vary.

  2. Separate it into an interface with a method declared for the behavior.

  3. Provide implementations for the separated interface.

  4. Code within the context class against the interface and inject the implementation at runtime

 

Benefits and usage of Strategy Pattern

  1. Strategy lets the algorithm vary independent of the classes that uses them.

  2. Strategy pattern is used when we need different variants of an algorithm within our class.

 

Examples

Example 1: array class with a sort method

We can have an array class with a sort method, and the sort technique to use may vary from bubble sort, merge sort, quick sort, insertion sort etc. based on various criteria. In this case, we can have an interface Sortable with a Sort method and its implementations as bubble sort, merge sort, quick sort, insertion sort etc. In the array class, we can have a sort method and then inject the implementation based on the criteria at runtime. Whenever someone call a sort of the array class, we can delegate the call to Sortable.sort(), which will call the sort() method of the implementation that is injected in.

public interface Sortable {

  public void sort();

}

public class MergeSort implements Sortable{

  public void sort()

  {

    //Implementation for merge sort

  }

}

MyArray{

  Sortable sortable;

  …

  MyArray()

  {

    sortable = new BubbleSort(); //default

  }

  …

  setSortable(Sortable sortable)

  {

  this.sortable = sortable;

  }

 

  Sort()

  {

  sortable.sort();

  }

}

Client code will pass on an implementation to the context class as:

MyArray myarray = new MyArray();

myarray.setSortable(new MergeSort());

myarray.sort();

You can now change the behavior even at runtime.

 

Example 2: Duck simulator class

The book Head First design patterns, give the example of a Duck simulator class. Duck may have behavior like fly, quack, swim etc. While some of these methods like swim are common for all, certain behavior like fly and quack may be different for different ducks in a simulation environment. One possibility is to have a common behavior in the parent and let all the children ducks override it. However if there are behavior which are common to more ducks, then all that ducks will need to duplicate that code everywhere that behavior is required. This will lead to the violation of the principle ‘Don’t repeat yourself (DRY)’.

There is also a probability of forgetting to override the common parent behavior which may lead to invalid cases. For instance, if the default behavior is fly and you forget to override it with no fly in a rubber duck, your rubber duck will be able to fly, which is an invalid case. To solve this, you may be tempted to use an interface and then implement the required behavior in each Duck class.  However if there are behavior which are common to more ducks, then all that ducks will need to duplicate that code everywhere that behavior is required. This will again lead to the violation of the principle ‘Don’t repeat yourself (DRY)’.

So a possible solution here is to use the strategy pattern. Encapsulate the fly behavior to a Flyable interface. The Flyable interface can have subclasses like FlyWithWings, NoFly etc. Duck class can have a reference to Flyable interface and we can inject FlyWithWings to ducks that can fly and NoFly to ducks like rubber ducks that can’t fly.

 

Relationships to design principles

  1. We are encapsulating the algorithm that varies and separating it into another class, which is what the principle ‘Encapsulate what varies’ suggest.

  2. We are also having a reference type of the abstract parent as a member variable in the class and injecting the right behavior class implementation, which is in accordance with the principle ‘Program to interfaces’.

  3. Instead of having this behavior in parent class and making all classes to override it, we are having the behavior class as a member of the context class, which is now a HAS-A relationship instead of IS-A relationship, thus preferring composition over inheritance.

  4. The context class received requests and delegates it to the injected strategy object. Hence it can also make use of the Dependency inversion principle (DIP).

  5. Strategy pattern also avoids the violation of the principle ‘Don’t repeat yourself (DRY)’ (refer to the second example for more details).​

 

Comparisons with similar patterns

From an interview perspective, it would be nice to know the differences between related patterns:

  • Strategy vs. Bridge

    • Though the diagrams for both Strategy and Bridge is same, they are different patterns. Different questions may have same answer, but the questions will still be different. Bridge is a structural pattern, whereas Strategy is a behavioral pattern.

    • The intent of Bridge pattern is to reduce the complexity in inheritance through the use of HAS-A along with IS-A, whereas the intent of Strategy pattern is to replace behavior (algorithms), and again through the use of HAS-A along with IS-A. 

  • Strategy vs. State

    • Both Strategy and State are behavioral patterns.

    • In case of strategy it is the client that decide which replacement part (algorithm) to use, by injecting the right implementation class. However, in case of state, it is the context object that decides which replacement part (state object) to use, based on the current state.

  • Strategy vs. Template

    • Both Strategy and Template are behavioral patterns.

    • Template pattern provide an abstract parent template class and uses inheritance to fill in the template class by its Children. A strategy pattern's replacement behavior is encapsulated into external classes and uses composition to use the right behavior.

 

References and notes: 
  1. Head First Design Patterns By Eric Freeman, Elisabeth Freeman, Bert Bates, Kathy Sierra
  2. Peeling Design Patterns Srinivasa Rao and Narasimha Karumanchi

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)