Example of the strategy pattern
To illustrate how to use the strategy pattern, let's consider a simple example of a calculator application that can perform different operations on two numbers. The operations are the algorithms that we want to encapsulate and make interchangeable.
First, we define the strategy interface, which declares a method called execute that takes two numbers as parameters and returns a number.
public interface OperationStrategy {
public double execute(double x, double y);
}
Next, we implement the concrete strategies, which are classes that implement the operation strategy interface and provide the specific logic for each operation. For example, we can have a class for addition, subtraction, multiplication, and division.
public class AdditionStrategy implements OperationStrategy {
public double execute(double x, double y) {
return x + y;
}
}
public class SubtractionStrategy implements OperationStrategy {
public double execute(double x, double y) {
return x - y;
}
}
public class MultiplicationStrategy implements OperationStrategy {
public double execute(double x, double y) {
return x * y;
}
}
public class DivisionStrategy implements OperationStrategy {
public double execute(double x, double y) {
return x / y;
}
}
Then, we define the context class, which is the calculator that uses an operation strategy to perform an operation on two numbers. It has a field to store the current strategy, a constructor to initialize it, and a method to set it. It also has a method to perform the operation, which invokes the execute method of the strategy object.
public class Calculator {
private OperationStrategy strategy;
public Calculator(OperationStrategy strategy) {
this.strategy = strategy;
}
public void setStrategy(OperationStrategy strategy) {
this.strategy = strategy;
}
public double performOperation(double x, double y) {
return strategy.execute(x, y);
}
}
Finally, we can use the calculator class and change its strategy at runtime, depending on the user's input or preference. For example, we can create a calculator object with an initial strategy of addition, and then change it to subtraction, multiplication, or division as needed.
public class CalculatorDemo {
public static void main(String[] args) {
Calculator calculator = new Calculator(new AdditionStrategy());
System.out.println(calculator.performOperation(10, 5)); // prints 15
calculator.setStrategy(new SubtractionStrategy());
System.out.println(calculator.performOperation(10, 5)); // prints 5
calculator.setStrategy(new MultiplicationStrategy());
System.out.println(calculator.performOperation(10, 5)); // prints 50
calculator.setStrategy(new DivisionStrategy());
System.out.println(calculator.performOperation(10, 5)); // prints 2
}
}