How to write a Singleton in proper manner?

后端 未结 13 1149
走了就别回头了
走了就别回头了 2020-12-23 12:03

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

    private static Singleton re         


        
13条回答
  •  被撕碎了的回忆
    2020-12-23 12:38

    Latest Standard Solutions:

    • Core java with Managed Beans / CDI

      @ApplicationScoped
      public class MySingleton { ... }
      
    • EJB Lite (JEE6)

      @Singleton
      public class MySingleton { ... }
      

    Prior Recommendation (from 'Effective Java 2'):

    • Use an enum, with a single bogus enumeration constant e.g. INSTANCE. Data fields and methods can be either static or non-static (instance) - the two behave equivalently, since there's only one instance

    • Advantages:

      • Yep, it's a singleton. Impossible to create more than one instance by any mechanism (within any given class loader on any JVM).
      • Singleton initialization is thread safe.
    • Disadvantages (compared with above Standard Solutions):

      • The definition is a little obtuse - the 'enum' outer shell could misdirect inexperienced code maintainers. It's a small hack, not the original intention of enum.
      • The implementation leaks through the abstraction. It violates the Uniform Access Principle
        • It doesn't work via injection - the client must know it is a singleton & code against the precise enum instance
        • The client must use Singleton.INSTANCE.someMethod()
        • The client can't (simply) code against an interface
        • The client's impacted by design changes between singleton to/from multi-instance objects
      • Extends an ancestor class (Enum), preventing inheritance from other classes
      • Serialization & deserialization just transfer the enum constant name without state - good for technically ensuring there's only one instance, but a null operation with regards to data. In the (rare) event one wanted to share/synchronise singleton state across JVMs/class loaders, replication via serialization couldn't be used.

提交回复
热议问题