Skip to content
Related Articles

Related Articles

How to Implement a Strategy Pattern using Enum in Java?
  • Last Updated : 22 Feb, 2021

The strategy design pattern is intended to provide a way to choose from a variety of interchangeable strategies. Classic implementation includes an architecture to be implemented by each technique and offers a concrete implementation for execution. The method is chosen from an interface reference, and the execution method is called.

The classic implementation of the Strategy design pattern:

The strategy interface must be implemented by all strategies.

public interface Strategy {
  public void execute();
}

All strategies must implement the strategy interface two classes showing the implementation of the Strategy interface and created an execute method.

public class StrategyA implements Strategy {
 @Override
 public void execute(){
   System.out.print("Executing strategy A");
 }
}
public class StrategyB implements Strategy {
 @Override
 public void execute() {
   System.out.print("Executing strategy B");
 }
}

The main class will select the strategy and execute the execute method of the strategy we chose.



public class GFG {

 private Strategy strategy;

 public void setStrategy(Strategy strategy){
   this.strategy = strategy;
 }

 public void executeStrategy(){
   this.strategy.execute();
 }
}

An example of using the Strategy.

public class UseStrategy {

public static void main(String[] args){

Context context = new Context();

context.setStrategy(new StrategyA());
context.executeStrategy();

context.setStrategy(new StrategyB());
context.executeStrategy();
}
}

Enum implementation of the Strategy design pattern:

It will have two classes: an enum class and a class that uses it. All the magic happens in the enum, where the concrete implementation of the strategy is done to define each enum constant.

Java




// Java program to Implement a Strategy Pattern using Enum
  
enum Strategy {
  
  STRATEGY_A {
    @Override
    void execute() {
      System.out.println("Executing strategy A");
    }
  },
    
  STRATEGY_B {
    @Override
    void execute() {
      System.out.println("Executing strategy B");
    }
  };
  
  abstract void execute();
}
  
  
 class UseStrategy {
  
  public static void main(String[] args)
  {
    UseStrategy useStrategy = new UseStrategy();
    useStrategy.perform(Strategy.STRATEGY_A);
    useStrategy.perform(Strategy.STRATEGY_B);
  }
  
  private void perform(Strategy strategy) {
    strategy.execute();
  }
}
Output
Executing strategy A
Executing strategy B

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :