Monday, 18 April 2016

Design Patterns : singleton / Single Object class


Here is the simple definition.

Single Object class have its constructor as private and have a static instance of itself.

Explanation:

1. Private constructor:  This stops us creating object for the class, Not even one object creation is allowed.

But, we want one object.
How can we create it?

2. Static instance of itself: Create a instance of self and mark it as static.

'Static' help us to access the instance with out creating object ( Anyways with the point#1, we can not create instance )


public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
    
}

// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

 

No comments:

Post a Comment