3

I'm trying to understand the strategy pattern and enums in java. I've googled this and have found a few articles on the subject, but most of them seemed too complex for my understanding. Could anyone provide a simple example or another link that demonstrates strategy pattern using enums in laymen terms using java?

Thanks you in advance.

michaelok
  • 1,124
  • 1
  • 13
  • 20
Horse Voice
  • 8,138
  • 15
  • 69
  • 120
  • 2
    Asking for external resources is off-topic. Why does the example have to apply to enums? The strategy pattern is completely independent of enums. Do you understand the pattern itself? Do you understand what an enum is? – Sotirios Delimanolis Jun 26 '14 at 15:56
  • I think below is an awesome example and works perfectly for what I was looking for!!! Thanks. I wanted an enum example. Not an overly verbose class filled example. – Horse Voice Jun 26 '14 at 18:13

1 Answers1

15

This should do:

interface Strategy {

    int execute(int a, int b);
}

enum Math implements Strategy {

    Add {

                @Override
                public int execute(int a, int b) {
                    return a + b;
                }
            },
    Subtract {

                @Override
                public int execute(int a, int b) {
                    return a - b;
                }
            },
    Multiply {

                @Override
                public int execute(int a, int b) {
                    return a * b;
                }
            };
}

It is a re-implementation of the Wikipedia article using enum for the strategies.

Or a little longer but more clearly a strategy pattern:

public interface FailureStrategy {
    void fail (String message);
}

enum Failure implements FailureStrategy {
    Ignore {

        @Override
        public void fail(String message) {
            // Do nothing on success.
        }

    },
    LogToConsole {

        @Override
        public void fail(String message) {
            System.out.println(message);
        }

    },
    ErrToConsole {

        @Override
        public void fail(String message) {
            System.err.println(message);
        }

    },
    RingAlarmBells {

        @Override
        public void fail(String message) {
            // Left to the student.
        }

    },
    SoundTheKlaxon {

        @Override
        public void fail(String message) {
            // Left to the student.
        }

    },
    EndTheWorld {

        @Override
        public void fail(String message) {
            // Left to the student.
        }

    };
}

public class SomethingLethal {
    public FailureStrategy onFail = Failure.EndTheWorld;
}

public class SomethingDangerous {
    public FailureStrategy onFail = Failure.RingAlarmBells;
}

public class SomethingBenign {
    public FailureStrategy onFail = Failure.Ignore;
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Nice. Without the interface, and having a (3 times ovverriden) base function `int execute(int a, int b)` one already could call this a strategy pattern, nicely compact. – Joop Eggen Jun 26 '14 at 16:08
  • 1
    Note: enum constants should be all capital case. – Puce Jun 26 '14 at 16:42
  • 2
    @Puce - I never let dogma get in the way of readability. :) – OldCurmudgeon Jun 26 '14 at 18:43
  • @OldCurmudgeon That's OK. But do you think e.g. `LogToConsole` is easier to read and to be recognized as a constant than `LOG_TO_CONSOLE`? – Puce Jun 27 '14 at 07:49
  • 3
    @Puce - My IDE knows it as a constant and colours it for me to remind me. I don't need to mangle my code to support an archaic and IMHO bad naming convention. A wise man understands the difference between a dogma and a mantra. :) I'm not going to shout in my code just to adhere to a coding standard. – OldCurmudgeon Jun 27 '14 at 08:19
  • No need to create a new interface. You can create a abstract method in enum, like this: abstract int execute(int a, int b); – Wendel Oct 17 '17 at 13:22
  • 1
    @Wendel - True, but exposing only the `interface` reduces the overall exposure to a minimum which is usually a good idea. The alternative would be to expose the whole `Enum` which would allow users to take liberties, which, of course, they will. – OldCurmudgeon Oct 17 '17 at 14:21