What are enums and why are they useful?

后端 未结 27 1898
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  甜味超标
    2020-11-22 07:17

    Enum inherits all the methods of Object class and abstract class Enum. So you can use it's methods for reflection, multithreading, serilization, comparable, etc. If you just declare a static constant instead of Enum, you can't. Besides that, the value of Enum can be passed to DAO layer as well.

    Here's an example program to demonstrate.

    public enum State {
    
        Start("1"),
        Wait("1"),
        Notify("2"),
        NotifyAll("3"),
        Run("4"),
        SystemInatilize("5"),
        VendorInatilize("6"),
        test,
        FrameworkInatilize("7");
    
        public static State getState(String value) {
            return State.Wait;
        }
    
        private String value;
        State test;
    
        private State(String value) {
            this.value = value;
        }
    
        private State() {
        }
    
        public String getValue() {
            return value;
        }
    
        public void setCurrentState(State currentState) {
            test = currentState;
        }
    
        public boolean isNotify() {
            return this.equals(Notify);
        }
    }
    
    public class EnumTest {
    
        State test;
    
        public void setCurrentState(State currentState) {
            test = currentState;
        }
    
        public State getCurrentState() {
            return test;
        }
    
        public static void main(String[] args) {
            System.out.println(State.test);
            System.out.println(State.FrameworkInatilize);
            EnumTest test=new EnumTest();
            test.setCurrentState(State.Notify);
            test. stateSwitch();
        }
    
        public void stateSwitch() {
            switch (getCurrentState()) {
            case Notify:
                System.out.println("Notify");
                System.out.println(test.isNotify());
                break;
            default:
                break;
            }
        }
    }
    

提交回复
热议问题