Java Singleton Design Pattern : Questions

后端 未结 11 683
渐次进展
渐次进展 2021-01-30 11:39

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can i

11条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 12:21

    There are a few ways to implement a Singleton pattern in Java:

    // private constructor, public static instance
    // usage: Blah.INSTANCE.someMethod();
    public class Blah {
        public static final Blah INSTANCE = new Blah();
        private Blah() {
        }
        // public methods
    }
    
    // private constructor, public instance method
    // usage: Woo.getInstance().someMethod();
    public class Woo {
        private static final Woo INSTANCE = new Woo();
        private Woo() {
        }
        public static Woo getInstance() {
            return INSTANCE;
        }
        // public methods
    }
    
    // Java5+ single element enumeration (preferred approach)
    // usage: Zing.INSTANCE.someMethod();
    public enum Zing {
        INSTANCE;
        // public methods
    }
    

    Given the examples above, you will have a single instance per classloader.

    Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?

    Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".

提交回复
热议问题