Announcement Announcement Module
Collapse
No announcement yet.
Enum implementation of the Singleton pattern Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Enum implementation of the Singleton pattern

    Joshua Bloch, author of "Effective Java", (along with others) is promoting the implementation of Singletons using the Java Enum type.
    Code:
    public enum MySingleton implements MyFunctionality
    {
       INSTANCE;
    
       // MyFunctionality goes here...
    }
    My question is whether the Spring IOC container will fully support and recognize this implementation as a true Singleton.

    I've already encountered a situation where I had to provide a static getInstance() method on a Singleton of this type, in order to get the ApplicationContext to return the bean (using only the interface type to retrieve it) as follows:
    Code:
    bean = appContext.getBean(MyFunctionality.class);
    Of course, I might have had other factors influencing that particular situation. A simple test verified that the getInstance() method is not necessary in all cases when retrieving the bean as above.

    Can anyone more familiar with the inner workings of the IOC container comment on how Spring might handle this new Singleton implementation?

  • #2
    Effective java

    What is instance control?

    Instance control basically refers to single instance of the class OR singleton design pattern .

    Java 1.5 onwards we should always prefer ENUM to create singleton instance. It is absolutely safe . JVM guarantees that. All earlier mechanical of controlling instance to single are already broken.

    So in any interview you can confidently say ENUM= provides perfect singleton implementation .

    Now what is readResolve?

    readResolve is nothing but a method provided in serializable class . This method is invoked when serialized object is deserialized. Through readResolve method you can control how instance will be created at the time of deserialization.Lets try to understand some code

    public class President {

    private static final President singlePresident = new President();

    private President(){

    }

    }

    This class generates single instance of President class. singlePresident is static instance and same will be used across.

    But do you see it breaks anywhere?


    Please visit http://efectivejava.blogspot.in/ for more details on this

    Comment

    Working...
    X