How to Implement a Strategy Pattern using Enum in Java?


The Strategy pattern is a design pattern that belongs to the Behavioral group. It enables developers to define a set of algorithms by creating separate classes for each one, and at runtime, change them as needed. Java provides several approaches to implement the Strategy pattern; Enumerations are a popular method used in our case. An Enumeration is useful when you need to create a fixed list of constants that represent different strategies in your program's logic.

To easily switch between different strategies in Java using the Strategy pattern, defining an Enum that represents these strategies is a clean and concise approach. By selecting the appropriate Enum constant, this method allows for seamless changes between the various options.

Enum

An Enum in Java is a unique data type comprising a fixed set of constants. It provides the ability to create values that are mutually exclusive within the Enum type and can be referred to as an Enum constant. This special feature enables you to define named values, making your code more readable and concise:

enum DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

The Enum type called DayOfWeek is an example that represents all the seven days of a week. It includes Monday, Tuesday, We­dnesday, Thursday, Friday, Saturday and Sunday as constants. Throughout the codebase users can access these predefined values within the Enum type.

Approaches

There are multiple ways to implement the Strategy pattern using Enum in Java. Here are two common approaches:

  • Enum with abstract method

  • Enum with functional interface

Enum with abstract method

In an Enum with abstract methods, each Enum constant overrides an abstract method declared in the Enum. This allows each constant to provide its own implementation of the strategy. The abstract method serves as a contract that all Enum constants must fulfill, ensuring that each constant defines the required behavior for the strategy it represents.

Algorithm

  • Define an Enum to represent the strategies.

  • Declare an abstract method within the Enum to represent the strategy behavior.

  • Create Enum constants within the Enum, each implementing the abstract method with its unique strategy implementation.

  • The abstract method serves as a contract that all Enum constants must fulfill, ensuring each constant defines the required behavior.

  • Client code can access the desired strategy by invoking the abstract method on the appropriate Enum constant.

  • The strategy implementation can be switched by selecting a different Enum constant.

  • This approach provides a clear and consistent way to define and execute strategies within the Enum.

Example

enum CalculationStrategy {
   ADDITION {
      @Override
      public int calculate(int a, int b) {
         return a + b;
      }
   },
   SUBTRACTION {
      @Override
      public int calculate(int a, int b) {
         return a - b;
      }
   };

   public abstract int calculate(int a, int b);
}

public class Main {
   public static void main(String[] args) {
      int a = 10;
      int b = 5;

      CalculationStrategy strategy = CalculationStrategy.ADDITION;
      int result = strategy.calculate(a, b);
      System.out.println("Addition Result: " + result);

      strategy = CalculationStrategy.SUBTRACTION;
      result = strategy.calculate(a, b);
      System.out.println("Subtraction Result: " + result);
   }
}

Output

Addition Result: 15
Subtraction Result: 5

Enum with functional interface

An Enum with a functional interface associates an instance of the functional interface with each Enum constant. The functional interface defines a single method that represents the strategy behavior. Each Enum constant is initialized with a lambda expression or a method reference that implements the functional interface's method. This approach provides a concise way to define and execute strategies within an Enum using functional programming concepts.

Algorithm

  • Define an Enum to represent the strategies.

  • Create a functional interface that declares a single method representing the strategy behavior.

  • Associate an instance of the functional interface with each Enum constant.

  • Initialize each Enum constant with a lambda expression or method reference that implements the functional interface's method.

  • Client code can execute the desired strategy by invoking the method of the functional interface on the appropriate Enum constant.

  • The strategy implementation can be easily switched by selecting a different Enum constant.

  • This approach utilizes functional programming concepts to provide concise and flexible strategy implementations within the Enum.

Example

enum CalculationStrategy {
   ADDITION((a, b) -> a + b),
   SUBTRACTION((a, b) -> a - b);

   private final CalculationOperation operation;

   CalculationStrategy(CalculationOperation operation) {
      this.operation = operation;
   }

   public int calculate(int a, int b) {
      return operation.operate(a, b);
   }

   interface CalculationOperation {
      int operate(int a, int b);
   }
}

public class Main {
   public static void main(String[] args) {
      int a = 10;
      int b = 5;

      CalculationStrategy strategy = CalculationStrategy.ADDITION;
      int result = strategy.calculate(a, b);
      System.out.println("Addition Result: " + result);

      strategy = CalculationStrategy.SUBTRACTION;
      result = strategy.calculate(a, b);
      System.out.println("Subtraction Result: " + result);
   }
}

Output

Addition Result: 15
Subtraction Result: 5

Conclusion

In this tutorial, the Strategy pattern implemented using Enum with abstract method or Enum with functional interface in Java provides a structured and flexible approach to define and switch between different strategies. It allows for clean code organization, promotes code reusability, and enables easy extension of strategies. The choice between abstract method and functional interface depends on the specific requirements and coding style preferences, offering different ways to achieve the desired strategy behavior.

Updated on: 25-Jul-2023

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements