LCWD LogoLearn Code With DurgeshLCWD
HomeCoursesTutorialsBlogsContact
About LCWDAbout Durgesh Tiwari
Flex Box Hero
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
  • FlexBox Game

Legal

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

Contact

  • 📞 +91-9839466732
  • [email protected]
  • 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 durgeshkumar8896 • 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...

The Future of Technology: Quantum Computing and Its Ecosystem

The Future of Technology: Quantum Computing and Its Ecosystem

Quantum computing isn’t just another buzzword—it’s a completely new way of thinking about computers. Unlike our everyday laptops or phones that run on classical computing, quantum computers use the strange but powerful rules of quantum mechanics.

Tailwind CSS Cheat Sheet – Complete Utility Class Guide 2025

Tailwind CSS Cheat Sheet – Complete Utility Class Guide 2025

Tailwind CSS Cheat Sheet – Complete Utility Class Guide 2025

Expert-Level JavaScript Interview Q&A for 2025: Crack Advanced JS Interviews

Expert-Level JavaScript Interview Q&A for 2025: Crack Advanced JS Interviews

Get ready for tough coding interviews with this collection of advanced JavaScript interview questions and answers. Designed for experienced developers who want to master complex JS concepts and impress recruiters.

Ace Your Coding Interview: JavaScript Q&A for Intermediate Learners

Ace Your Coding Interview: JavaScript Q&A for Intermediate Learners

Prepare for your next coding interview with this collection of JavaScript interview questions and answers for intermediate developers. Strengthen your JS concepts and boost your confidence.

Most Asked JavaScript Interview Questions with Answers

Most Asked JavaScript Interview Questions with Answers

Q1. What is JavaScript? JavaScript is a programming language mainly used to make web pages interactive and dynamic. It runs in the browser, and with Node.js, it can also run on the server.

The 5 ChatGPT Prompts That Saved Me From Burnout

The 5 ChatGPT Prompts That Saved Me From Burnout

Here’s what I discovered: It wasn’t about working less. It was about working smarter. When I gave ChatGPT the right prompts, everything changed. Here are the 5 prompts that transformed my productivity:

Share this article ...

💬WhatsApp📘Facebook💼LinkedIn🐦X