Learn Code With Durgesh LogoLCWD
HomeCoursesBlogsContact Us
HomeCoursesBlogsContact Us
LearnCodeWithDurgesh Logo

Learn Code With Durgesh

Offering free & premium coding courses to lakhs of students via YouTube and our platform.

Explore

  • About Us
  • Courses
  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Support

Contact

  • 📞 +91-9839466732
  • support@learncodewithdurgesh.com
  • Substring Technologies, 633/D/P256 B R Dubey Enclave Dhanwa Deva Road Matiyari Chinhat, Lucknow, UP, INDIA 226028
© 2025 Made with ❤️ by Substring Technologies. All rights reserved.
Singleton Design Pattern

Singleton Design Pattern

By durgesh • Thu May 18 2023

Singleton Design Pattern

Singleton Design Pattern

The Singleton design pattern is a creational design pattern that restricts the instantiation of a class to a single object and provides global access to that instance throughout the application. This pattern ensures that only one instance of a class is created and provides a global point of access to it.

Singleton Object

Singleton object are the object which are instantiated only once for project (jvm). If we try to get the object then we get same object again and again.

lets create object using singleton pattern using java

Lazy way of creating singleton object

class Example{


private static Example ob;

public static Example getExample(){
    if(ob==null){
        ob=new Example();
    }
    return ob;
}


}

calling the singleton object

class Main
{
    public static void main(String args[]){
        Example ob=Example.getExample()
        //using the object

    }
    }
}

Eager way of creating Singleton object

class Example{


private static Example ob=new Example();

public static Example getExample(){
      return ob;
}


}

Accessing object

class Main
{
    public static void main(String args[]){
        Example ob=Example.getExample()
        //using the object

    }
    }
}

note: for multithreaded environment we use syncronized block for creating singleton object.

class Example{


private static Example ob;

public static Example getExample(){
    if(ob==null){
      syncronized(Example.class){
        if(ob==null)
        {
              ob=new Example();
        }
      }
    }
    return ob;
}


}

Breaking Singleton Design Pattern

There are three ways to break singleton design pattern . Lets talk about it. I am also going to tell you about the solution of these problems.

1. Using Reflection API

With the help of relfection api we can call private constructor  and create multiple object by calling private constructor.

lets see how we can call private constructor

Constructor<Example> constructor=Example.class.getDeclaredConstructor()

//changing the accessibility to true
constructor.setAccessible(true)

Example example=constructor.newInstance();

solution

we can do the soultion in two ways.

  1. using ENUM
public enum Example{
    INSTANCE
}
  1. check the object in private constructor if the object exists then throw exception to terminate the execution.
private Exmaple(){

    if(ob!=null)
    {
        throw new RuntimeExcepiton("you are trying to break singleton pattern")
    }
}

2. Using Deserialization

when we serialize and deserialize the singleton object then singleton pattern automatically got destroyed and provide us different object.

ObjectOutputStream oos = new ObjectOutputStream(new
        FileOutputStream("abc.ob"));
        oos.writeObject(ob);

        System.out.println("serialization done..");

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("abc.ob"));
        Example s2 = (Example) ois.readObject();
        System.out.println(s2.hashCode());

solution:

just implement readResolve() method

 public Object readResolve() {
        return ob;
    }

3. Using cloning

when we clone then also we get different object.

solution

just override clone method and return the same instance.

 @Override
    public Object clone() throws CloneNotSupportedException {
        return samosa;
    }

Video Link:

Singleton Design Pattern:

Breaking of Singleton design Pattern:

Share this article ...

💬WhatsApp📘Facebook💼LinkedIn🐦X

Trending Blogs...

Maven Tutorial

Maven Tutorial

Maven is a build automation tool primarily used for Java projects. It addresses two main aspects of building software: dependency management and project build lifecycle management.

Important DSA Topics for placements

Important DSA Topics for placements

Data Structures and Algorithms (DSA) are fundamental building blocks of computer science. A strong understanding of DSA is essential for every developer, regardless of their specialization.

Amazing Windows key shortcuts in Windows 11

Amazing Windows key shortcuts in Windows 11

Shortcuts are everyone’s favorite, be it in life or in Keyboard. We don’t know about life but we have some amazing shortcut tricks for your keyboard, which are newly introduced in windows 11. Let's have a look and understand these amazing shortcuts to reduce our finger pain

Share this article ...

💬WhatsApp📘Facebook💼LinkedIn🐦X