Header Ads

  • Breaking Now

    What is Singleton Design Pattern?

    The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

    In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.
    public class SingletonClass {
    private static SingletonClass instance = null;
    protected SingletonClass() {
    // can not be instantiated.
    }
    public static SingletonClass getInstance() {
    if(instance == null) {
    instance = new SingletonClass();
    }
    return instance;
    }
    }

    In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.

    public class SingletonInstantiator {
    public SingletonInstantiator() {
    SingletonClass instance = SingletonClass.getInstance();
    SingletonClass anotherInstance =
    new SingletonClass();
    ...
    }
    }
    

    In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

    4 comments:

    1. This is good
      But i want some information which situation we can use singleton in cloning

      ReplyDelete
    2. The above code was the common implementation but there will be different implementation in case of cloning and multi-threaded environment. Refer to following link: http://javadevelopershelp.blogspot.com/2009/02/singleton-pattern-in-java.html

      ReplyDelete
    3. Aniket:
      Thanks for sharing the information.

      ReplyDelete
    4. The constructor for the singleton class should not be protected but private.

      ReplyDelete

    Post Top Ad

    Post Bottom Ad