Design Patterns - SPLessons
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. [java] public interface Operation { public int operation(int num1, int num2); }[/java] Creating a class AddOperation and implementing the Operation interface . [java] public classAddOperation implements Operation { public int operation(int num1, int num2)//overrides the interface methods { return num1 + num2; } }[/java] Creating a class MultiplyOperation and implementing the Operation interface. [java] public class MultiplyOperation implements Operation { public int operation(int num1, int num2)//overrides the interface method { return num1 * num2; } }[/java] Creating a class SubstractOperation and implementing the Operation interface. [java] public class SubstractOperation implements Operation { public int operation(int num1, int num2)//overrides the interface method { return num1 - num2; } }[/java] Creating a class ContextOperation. [java] 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); } }[/java] Creating a class StrategyPattern and objects. [java] 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)); } }[/java]

shape Output

The result will be as follows. [java] 10 + 50 = 60 10 * 10 = 100 10 - 6 = 4 [/java]

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.