This tutorial aims to guide you through the process of implementing a strategy pattern in your code. This is an essential aspect of Object-Oriented Programming (OOP) that helps in organizing code based on its behavior.
You'll learn about the strategy pattern, its importance, and how to implement it in a Java program. This will include creating various classes and interfaces to mimic a real-world problem.
You should have a basic understanding of Java programming language, including knowledge of classes, interfaces, and methods.
The Strategy Pattern is a type of behavioral design pattern that encapsulates a "family" of algorithms and selects one from the pool for use during runtime. By using this pattern, the algorithms can be independently from clients that use them.
// Strategy interface
public interface Strategy {
public int doOperation(int num1, int num2);
}
// Concrete strategy classes implementing the strategy interface
public class OperationAdd implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class OperationSubstract implements Strategy {
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
// Context class that uses a Strategy
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
// Using the Context to see change in behaviour when it changes its Strategy.
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
}
}
In this example, we first create a Context
object with OperationAdd
strategy. We then execute the strategy and print the result. Next, we change the strategy of the Context
to OperationSubstract
, execute the strategy, and print the result.
10 + 5 = 15
10 - 5 = 5
Create a new strategy called OperationMultiply
that multiplies two numbers and integrate it into the existing code.
Modify the Context
class so that it can accept and use multiple strategies at runtime.