Skip to main content

SingleTon DesignPattern

Singleton pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and with Singleton Pattern we will allow only one instance of the class to be created. Here in this article we will understand how we can create an Singleton class in Java.

Singleton Class Code:
package designpattern.creational.singleton;
public class MySingleTon {
   private MySingleTon() {
   }

   private static MySingleTon instance = null ;

   public static synchronized MySingleTon getInstance() {
      if(instance == null) {
          System.out.println("Creating New Instance");
          instance = new MySingleTon();
} else {
    System.out.println("Returning Existing Instance");
}
return instance;
   }

   public Object clone() throws CloneNotSupportedException {
       throw new CloneNotSupportedException();
   }
}
Code Explanation:
  • Why the constructor declared private? – This is required so that the Singleton class could not be instantiated by any other class.
  • Why the getInstance() method is synchronized? – This is required so that at any point of time only single class can access the Singleton Class. which means at any point of time we can have only single instance of class going outside the singleton class.
  • Here we have created an static instance of MySingleTon Object, this object will be returned whenever user calls the Singleton class.
  • Inside getInstance() we check whether the static instance of Singleton class holds the object if yes than we return the object else we create an new instance of the class.
  • You must be wondering why clone method is written here. This is required so that we are not able to clone this class and create multiple instance of the SingleTon Class.

Client Code:
package designpattern.creational.singleton;
public class SingleTonClient {

     public static void main(String[] args) {
 //Will not compile, throw an error
 MySingleTon s0 = new MySingleTon(); 

 MySingleTon s0 = MySingleTon.getInstance();
 System.out.println("Count:- " + s0.hashCode());

 try {
  Thread.sleep(10);
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

 MySingleTon s1 = MySingleTon.getInstance();
 System.out.println("Count:- " + s1.hashCode()); 

 MySingleTon s2 = MySingleTon.getInstance();
 System.out.println("Count:- " + s2.hashCode()); }
}
Here if you see if you try to create an new object of MySingleTon class, the java compiler will give an error that “Constructor MySingleton is not visible”. Then we try to access the object of the Singleton class and to cross check the hashcode printed is the same.

Comments

Popular posts from this blog

Mobile Message Organizer

Got a basic requirement that i think every mobile should have, all the mail clients have this facility and i dont see any big difficulties on this other than the storage problem which is not a problem at all as we got GB of spaces in our memory cards. Well i am talking about the organizing the messages in Inbox , categorization of messages. Suppose i want to store all the messages from one of my friend say A in a folder called Personal, my existing mobile device Nokai E71 doesn't have this feature inbuilt (Ofcourse if you want you can make a folder and move the messages manually but here i am talking about the idea of automating this procedure). Only thing we need to do is , we have to store the rules in separate location , rules will be defined by the user and then device will follow these rules.There are no or very less software available which satisfy this requirement for mobile device.this is so simple but basic requirement as per the end user. I am going to make this one ...

Interview : Shiv Khera

Winning as a way of life Shiv Khera, motivational expert, speaker, consultant and author of three best-selling books, does not necessarily speak about new things. His subject is human life – the individual vis-à-vis society, and how the two can win. But it is the use of the right word at the right time in the right context in simple, evocative terms that sets him apart. Rajeev Nair met him in Dubai Charged – that is one word to describe the infectious persona of Shiv Khera, the motivational expert, hot in demand in the US professional circles to turn around company fortunes and develop the man power base. The Indian has been a US-resident for nearly three decades but hasn’t relinquished his Indian citizenship; he even contested the general elections from Delhi.

Indian Education System : Let's shape it

Good advice is always certain to be ignored, but that's no reason not to give it.                                                                                        By Agatha Christie   This is one of the things that I wanted to write from long back and per my opinion it should be matter of at most important for any educated person of India. Today in this article I would like  focus on reminding people about the importance of education and educational departments  no matter those are government related or privately held. Whatever we are to...