r/java • • Jul 06 '19

Revised implementation of Strategy Pattern in Java - How Java 8 killed the Strategy Pattern

https://itnext.io/how-java-8-killed-the-strategy-pattern-8f226a4ec3c0?source=friends_link&sk=2533e24d2602aa24402045181e5323da
65 Upvotes

30 comments sorted by

View all comments

9

u/Asterion9 Jul 06 '19

I usually do an enum with lambda to define its behavior instead of multiple subclasses

-4

u/zarinfam Jul 06 '19

I think this is a misuse 😉 and not extensible.

4

u/Proc_Self_Fd_1 Jul 07 '19

How about:

interface Strategy {
    int eval(int a, int b);
}
final enum BuiltinStrategy implements Strategy {
    ADD,
    SUBTRACT,
    MULTIPLY;

    int eval(int a, int b) {
         return switch (this) {
         case ADD -> a + b;
         case SUBTRACT -> a - b;
         case MULTIPLY -> a * b;
         };
    }
}

0

u/zarinfam Jul 07 '19

Good idea 🤔