Singleton Design Pattern with Example in Java

(1850 Views)


What is Singleton Design Pattern?

The Singleton Design Pattern is the simplest design pattern. Singleton Design Pattern means a Class will have only one Instance. A singleton pattern is used when you need to manage a shared resource.

Some Examples where Singleton Pattern is used:

  1. A printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.
  2. A single Database connection is shared by multiple objects as creating a separate Database connection for each object is very costly task.
  3. Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively.
Implementing Singleton Design Pattern in Java

Singleton Design Pattern Definition:

The singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Singleton Design Pattern Program in Java:

package com.india.states; public class Maharashtra { // As the constructor is private, no one outside //this class can create an object of this class private Maharashtra() { System.out.println("Maharashtra Created"); } // only one instance of the class is created as the instance is static private static Maharashtra mah=new Maharashtra(); // one instance will be shared only by this method public static Maharashtra getInstance() { return mah; } }

In the above program, Maharashtra class is a Singleton class. As it is a singleton Class only one instance of Maharashtra class should be created. Steps for implementing Singleton pattern:

  1. Make the constructor of Class private, which would restrict instance creation from outside the "Maharashtra" class.
  2. Create an instance inside the "Maharashtra" Singleton Class with "static" access specifier. Because static keyword specifies that the variable belongs to a class.
  3. Create a public method, using which other classes can get the same instance of "Maharashtra" class created above.
  4. To get instance of "Maharashtra" Singleton class from other class, call it using this syntax:
  5. Maharashtra m=Maharashtra.getInstance();

Solution Worked 7 UpvotesUpvote

        

Solution Didn't Worked 2 DownvotesDownvote



Comments

1 comment
  • nam

    Use enum for Pete's sake.



Search
Play 2048 Game Online

Search Tags

    Singleton Design Pattern in Java

    Implement Singleton Design Pattern in Java

    Singleton Design Pattern Uses