Basic Strategy Example

This program demonstrates Strategy pattern.

Problem Statement

Write a Java program where different strategies are applied at runtime.

Source Code

1 interface Strategy { void execute(); }
2 class StrategyA implements Strategy {
3 public void execute(){ System.out.println("Executing Strategy A"); }
4 }
5 class StrategyB implements Strategy {
6 public void execute(){ System.out.println("Executing Strategy B"); }
7 }
8 class Context {
9 Strategy s;
10 Context(Strategy s){ this.s=s; }
11 void perform(){ s.execute(); }
12 }
13 public class StrategyBasic {
14 public static void main(String[] args) {
15 System.out.println("Eduinq Strategy Basic");
16 Context c=new Context(new StrategyA());
17 c.perform();
18 c=new Context(new StrategyB());
19 c.perform();
20 }
21 }

Program Output

Eduinq Strategy Basic
Executing Strategy A
Executing Strategy B

Explanation

Strategy defines algorithm interface. - Context uses different strategies at runtime. - This promotes flexibility and adherence to OCP. Conclusion: Shows how to implement Strategy pattern.

Quick Links to Explore