Monday, March 23, 2015

How to create Singleton class in java?

Step 1: Create Class “SingleObject.java”
Step 2: Create a private constructor so no one can instantiate  this class.
Step 3: Create the static method getInstance and this will return the object of SingleObject class.
Step 4: Create client program and call this static method of SingleObject class this method will return the same object each time.
Step 5: We can verify the the singleton behavior by hashCode. The hasCode is same for both object.



SingleObject.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package com.ashish.singletontest;
 
public class SingleObject {
 
   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();
 
   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}
 
   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }
 
   public void showMessage(int a){
      System.out.println("Hello World! : "+a);
   }
}

SingletonPatternDemo.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.ashish.singletontest;

public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();
      SingleObject object1 = SingleObject.getInstance();

      //show the message
      object1.showMessage(20);
      object.showMessage(30);
      object1.showMessage(30);
      System.out.println(("hashCode object : "+object.hashCode());
      System.out.println(("hashCode object1 : "+object1.hashCode());
      System.out.println(object1==object);
      System.out.println(object1.equals(object));
     
   }
}

Output:

Hello World! : 20
Hello World! : 30
Hello World! : 30
hashCode object : 17008065
hashCode object1 : 17008065
true
true

Note : Observe both the hasCode are same  17008065.

No comments :

Post a Comment