Share on Google+Share on Google+

Singleton Design Pattern

This example explores how to implement a SingletonPattern on a class in java.

Singleton Design Pattern


This example explores how to implement a SingletonPattern on a class in java.

The Singleton design pattern ensures that only one instance of a class is created, it provides a global point of access to the object and allow multiple instances in the future without affecting a singleton class's clients. To ensure that only one instance of a class is created we make SingletonPattern as static. getInstance() method returns a single instance of the class. We create a private default constructor to avoid outside modification.

This example gets instances of SingletonPattern two times but the method getInstance() will return the same object without creating a new one.

 The code of the program is given below:

public class SingletonPattern{
  private static SingletonPattern instance;
  private SingletonPattern(){} 
public static synchronized SingletonPattern getInstance(){
  if (instance == null)
  instance = new SingletonPattern();
  return instance;
public static void main(String arg[]){
  System.out.println("The output of two instance:");
  SingletonPattern sp=new SingletonPattern();
  System.out.println("First Instance: "+sp.getInstance());
  sp=new SingletonPattern();
  System.out.println("Second Instance:"+sp.getInstance());

The output of the program is given below:

C:\rajesh\kodejava>java SingletonPattern
The output of two instance:
First Instance: SingletonPattern@3e25a5
Second Instance:SingletonPattern@3e25a5

Download this example.



Posted on: July 6, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Singleton Design Pattern   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
June 14, 2011
Singleton Comments

Good one for singleton pattern.
October 5, 2011

This is not a proper singleton patter arse
March 24, 2012

its usefully but i want full describtion.....
June 4, 2012
Design pattern & Desing concepts

clearly explain above topics and realtime work environment where we use above topic
July 9, 2012
its not singleton

its not singleton
bhagyashri hadkar
July 26, 2012

too good!!!
August 24, 2012

Excellent Example! Thank You!
May 22, 2014
Wrong Example

How you can get the instance of a class with new operator if it's constructor is a private method ? Example main method is totally wrong.
September 1, 2011
singleton design pattern

give some example of how to use the singleton class from another class...thanks