Introduction
Strategy design pattern is a behavioral design pattern in which the behavior of the object is encapsulated with a common function name.
Where to use a Strategic design pattern?
We can use strategic design pattern when a different customer has a common strategy (Common operation name) but a different action to perform.
Why use a Strategic design pattern?
As discussed previously, customers have a common operation name to perform. With a strategic design pattern, we can share a common interface to all customers to perform their actions as per their need.
Players in this pattern
- Strategy: Defines a contract with a common operation.
- ConcreteStrategy: Implements contact defined by the Strategy.
- Product: Fulfills customer requirements using ConcreteStrategy objects by referring Strategy contract.
Now we will see a strategic design pattern with an example:
Problem definition: Define a common operation to student to access different actions like Addition, subtraction, multiplication, division.
Players in this case:
- Strategy: operator
- ConcreteStrategy: AddOperator, SubtractOperator, MultiplyOperator, DivisionOperator.
- Product: Calculator
Below is the operator contract which defines a common operation called ExecuteOperation:
- package com.sdp;
- public interface IOperator {
- void executeOperation(int a, int b);
- }
Below are the concrete operators which implement a contract as defined by the operator:
- package com.sdp;
- public class AddOperator implements IOperator {
- @Override
- public void executeOperation(int a, int b) {
- System.out.println("AddOperator result: " + (a + b));
- }
- package com.sdp;
- public class SubtractOperator implements IOperator {
- @Override
- public void executeOperation(int a, int b) {
- System.out.println("SubtractOperator result: " + (a - b));
- }
- }
- package com.sdp;
- public class MultiplyOperator implements IOperator {
- @Override
- public void executeOperation(int a, int b) {
- System.out.println("MultiplyOperator result: " + (a * b));
- }
- }
- package com.sdp;
- public class DivisionOperator implements IOperator {
- @Override
- public void executeOperation(int a, int b) {
- System.out.println("DivisionOperator result: " + (a / b));
- }
- }

Join the conversation! Your thoughts help the community grow.