Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
strategy pattern

What is the strategy pattern in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

svg viewer

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.

RELATED TAGS

java
strategy pattern
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring