1. Singleton Design Pattern (Creational types )

Singleton pattern 


What is a Singleton Design Pattern?

There are only two points in the definition of a singleton design pattern,

1) There should be only one instance allowed for a class and

2) We should allow global point of access to that single instance.

 - Singleton pattern will insure that only one instance of the class will be created by java virtual machine at any point of time. 

- It is used to provide global point of access to the object.Singleton patterns are used in logging, caches, thread pools,getting device driver objects etc.


Steps for Singleton Implementation  

1. private constructors :  if it public then we can create multiple object (Constructor use to initialize of object)

2. Static Instance: - we create static instance varible for holds the instance of the class.

- Within the Singleton class, there is a static member variable that holds the single instance of the class.

3. public static method : this method allow to other classes to acccess the single instance of object. & according to condition object will create once & if we access to get object then we get same object everytime.

4. Lazy initialization :  in lazy initailizatio instance will be created when when we request for it or we can created  at class Loading (eager initialization). 

- Lazy initialization is more prefered to save the resource if the instance is not always needed.


- up to above 4 step is good work its work not single thread & but if we want to use multiple then it will not work its will be create 2 object so in singleton we don't want to more than one object.

5. Make the Access method Synchronized :

In multi-threaded environment it may happen that two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects.Such problems can be avoided by defining getInstance() method synchronized.

-  we can use method synchronized Or we can use synchronized Block for Perticular block.


Here are some common use cases for the Singleton design pattern:

1. Database Connections

2. Thread Pools

3. Logging 


Program :  




class SingletonClass
{

    private static SingletonClass sc ;

    private SingletonClass()
    {

    }

    //  Thread Synchronizing 
    public synchronized static SingletonClass getInstance()
    {
        if(sc == null)
        {
            sc = new SingletonClass();
        }

        return sc;
    }

}


// Main Class
public class Singleton {
    
    public static void main(String[] args) {


        SingletonClass sc1 = SingletonClass.getInstance();
        System.out.println(sc1.hashCode()); // 1072591677

        SingletonClass sc2 = SingletonClass.getInstance();
        System.out.println(sc2.hashCode()); // 1072591677

    }
}




Comments

Popular posts from this blog

Introduction Design Pattern