java / intermediate
Snippet
The Strategy Pattern using Enums
In Java, Enums can have abstract methods that each constant must implement. This effectively implements the Strategy design pattern, allowing different behaviors to be associated with different enum constants.
snippet.java
1
2
3
4
5
6
7
8
9
10
public enum Operation {PLUS {public double apply(double x, double y) { return x + y; }},MINUS {public double apply(double x, double y) { return x - y; }};public abstract double apply(double x, double y);}
Breakdown
1
PLUS { public double apply(...) { ... } }
A specific implementation of the abstract method for the PLUS constant.
2
public abstract double apply(double x, double y);
Forces every constant in the enum to provide its own implementation of the logic.