Design Patterns - SPLessons

Strategy Pattern

Chapter 29

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Strategy Pattern

Strategy Pattern

shape Description

Strategy Pattern is a behavioral pattern used for changing the class and algorithm behavior at run time. In the Strategy Pattern, different objects are used to represent different strategies and a context object behavior changes according to the strategy object.

Multiple algorithms can be implemented and client can choose the required algorithm for implementation. Strategy pattern is similar to the state pattern and is known as “Policy Pattern”.

shape Advantages

  • Multiple algorithms can be implemented easily.
  • Behavior of the object can be changed easily.

shape Conceptual
figure

shape Examples

Creating an interface operation.

public interface Operation 
{
   public int operation(int num1, int num2);
}

Creating a class AddOperation and implementing the Operation interface .

public classAddOperation implements Operation
{
   public int operation(int num1, int num2)//overrides the interface methods
 {
      return num1 + num2;
   }
}

Creating a class MultiplyOperation and implementing the Operation interface.

public class MultiplyOperation implements Operation
{ 
   public int operation(int num1, int num2)//overrides the interface method
 {
      return num1 * num2;
   }
}

Creating a class SubstractOperation and implementing the Operation interface.

public class SubstractOperation implements Operation
{
   public int operation(int num1, int num2)//overrides the interface method 
{
      return num1 - num2;
   }
}

Creating a class ContextOperation.

public class Context
 {
   private Operation strategy;
   public Context(Operation strategy)
{
      this.strategy = strategy;
   }
   public int executeStrategy(int num1, int num2)
{
      return strategy.operation(num1, num2);
   }
}

Creating a class StrategyPattern and objects.

public class StrategyPattern
 {
   public static void main(String[] args) 
{
      Context context = new Context(new AddOperation());//creating object for context class		
      System.out.println("10 + 50 = " + context.executeStrategy(10, 50));
      context = new Context(new MultiplyOperation());		
      System.out.println("10 * 10 = " + context.executeStrategy(10, 10));
       context = new Context(new SubstractOperation());		
      System.out.println("10 - 6 = " + context.executeStrategy(10, 6));     
   }
}

shape Output

The result will be as follows.

10 + 50 = 60
10 * 10 = 100
10 - 6 = 4

Summary

shape Key Points

  • Strategy Pattern represents a set of algorithms and encapsulates each as a object.
  • Using Strategy pattern, the class behavior can be split into another class.