What is the strategy pattern in Java?
In the world of computer programming, the strategy design pattern is a pattern that enables users to select the strategy at runtime. More than one strategy can be implemented, and you can switch in-between them.
Choosing a strategy
The strategy pattern you choose depends on the type of data, the data’s source, user-choice, or any other factor; these factors may vary the pattern’s run-time. These factors may vary on run-time. Each strategy is encapsulated separately from the calling object.
Code
main.java
Strategy.java
Substract.java
Add.java
Context.java
public class main {public static void main(String[] arguments) {Context context = new Context(new Add());System.out.println("3 + 2 = " + context.executeStrategy(3, 2));context = new Context(new Substract());System.out.println("3 - 2 = " + context.executeStrategy(3, 2));}}
Explanation
In the code above, Strategy interface is implemented and a doAction() method is defined. The add and subtract classes implement this interface and override the doAction() method.
Now, the context sets up the strategy; it executes it later.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved