Strategy pattern using Enums. Need a simple example in Java [duplicate]

白昼怎懂夜的黑 提交于 2019-12-09 01:21:27

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/24435126/strategy-pattern-using-enums-need-a-simple-example-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!