Singleton pattern revisited


Singleton pattern

Definition: At any point of time we ensure that there is only object created for the class

Example:
participant classes:

  • Singleton.java
  • SingletonClient.java(client)

Diagram:

Singleton.java

  • This class includes a static member variable singleton with private scope
  • the constructor is private so that no one can instantiate it
  • we have a getCurrentInstance() method to instantiate the class. If the instance is already available then the instance is returned to the caller otherwise it is newly created
public class Singleton {

 private static Singleton singleton = null;

 private Singleton(){

 }

 public static synchronized Singleton getCurrentInstance(){
 if(singleton == null){
 return new Singleton();
 }
 else{
 return singleton;
 }
 }

 public void sayHello(){
 System.out.println("Hello");
 }
}

SingletonClient.java

use getCurrentInstance() method to get the instance of Singleton class and use it.

 public class SingletonClient {

 public static void main(String[] args) {

 Singleton singleton =  Singleton.getCurrentInstance();
 singleton.sayHello();
 }
}
 

contract:

cannot instatiate more than once.
getCurrentInstance() return only one instance at any point of time

3 thoughts on “Singleton pattern revisited

  1. Kedar

    Hi, this would cause all threads to be blocked as synchronised method being static. It is significant performance hit and application may not scale if there are numerous singletons.

    Is there any alternate? How about different class loaders?

    Thanks, Kedar

    Reply
  2. Pingback: Single object for Singleton pattern « They point the finger at me.. again!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s