Sunday 9 November 2014

Strategy Design pattern in Java

Background

In my previous post on Introduction to Design Patterns  we saw there are various types of Design patterns. They are mainly categorized into three types - 
  1. Creational
  2. Structural
  3. Behavioral
 In this post we will lean about Strategy Design pattern. This design pattern comes under behavioral type. This design patterns lets you  
  • define family of algorithms or class behaviors that can change at runtime depending on the context involved. To put it in other words 
  • it lets you choose your strategy from a list of predefined ones depending on what would suit your current runtime context.

Class Diagram




 Above class diagram represents the program that I will be using to demonstrate Strategy pattern. Points to note here -

  1. Both concrete type of Strategies i.e AdditionStrategy and SubtractionStrategy implement the interface Strategy that has a common method performOperation() that each implementing class implement.
  2. Also note the composition relationship between Strategy class and Calculator class. It simply means Calculator class owns Strategy class and that Strategy class cannot exist meaningfully without Calculator class.

To the Code

Lets first write own interface class - 

 Strategy.java

/**
 * 
 * @author athakur
 *
 */
public interface Strategy {
    
    public int performOperation(int a, int b);

}


Now lets write our concrete classes that implement above class -

AdditionStrategy.java


/**
 * 
 * @author athakur
 *
 */
public class AdditionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a+b;
    }

}

SubtractionStrategy.java

/**
 * 
 * @author athakur
 *
 */
public class SubtractionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a-b;
    }

}

and finally our Calculator class - Calculator.java


/**
 * 
 * @author athakur
 *
 */
public class Calculator {
    
    Strategy strategy;

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int calculate(int a, int b) {
        return strategy.performOperation(a, b);
    }

}

Now lets test our code. Create a class Test.java

/**

 * 

 * @author athakur

 *

 */

public class Test {

    public static void main(String args[]) {

        Calculator calc = new Calculator();

        calc.setStrategy(new AdditionStrategy());

        System.out.println("Additition : " + calc.calculate(5, 2));

        calc.setStrategy(new SubtractionStrategy());

        System.out.println("Subtraction : " + calc.calculate(5, 2));

    }

}

and the output will be as expected - 

Additition : 7
Subtraction : 3

Understanding the pattern via code

 See how we could change the operation using a particular strategy depending on the requirement. Calculator here is own context. When we needed addition we use the Addition Strategy and when we needed Subtraction we used the Subtraction strategy. Note how the context or the Calculator remains the same but the strategy used changes. We are simply using different strategies depending on the requirement at runtime. This type of design is called Strategy pattern.

To sum up -

In Strategy pattern, objects representing various strategies are created and a context object behavior changes depending on these strategies at runtime.

Related Links

t> UA-39527780-1 back to top