Pages

Tuesday, 10 September 2013

How to Create Singleton Class in Java, Singleton Class in Java



Making java class as singleton is very important in some real time projects, we may need to have exactly one instance of a class. Suppose in hibernate  SessionFactory should be singleton as its heavy weight, and some other Banking related projects mainly.
Some times creating singleton classes are very very important, if we are creating the object of some classes again and again ‘N’ number of times, that will definitely kills the memory and finally our application will get down, so we can avoid that with this concept.
Let us see how to..
Files required
  • AccountCreation.java
  • Client.java
AccountCreation.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
25
package single;

public class AccountCreation {

    private static AccountCreation instance;

       public synchronized static AccountCreation getInstance()
       {
           if (instance==null)
           {
              instance = new AccountCreation();
              System.out.println("AccountCreation Class Object creatred...!!!");
           }
          else{
              System.out.println("AccountCreation Class Object not Creatred just returned Created one...!!!");
          }
              return instance;
       }

       public void create(int no)
       {
          System.out.println("Account Created Successfully, with Number:" +no);
       }

}
Client.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package single;

public class Client {

  public static void main(String[] args)
  {

      AccountCreation tc = AccountCreation.getInstance();
      AccountCreation tc1 = AccountCreation.getInstance();

      tc.create(12345);
      tc1.create(67891);

  }
}

No comments:

Post a Comment