Singleton Design Pattern

Ads
 

Singleton Design Pattern

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

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>javac SingletonPattern.java
C:\rajesh\kodejava>java SingletonPattern
The output of two instance:
First Instance: [email protected]
Second Instance:[email protected]

Download this example.

Ads

Ads