SingleTon Class in Java



Imp. Points to Remember :

  • We can make constructor as private. So that We can not create an object outside of the class.
  • This property is useful to create singleton class in java.
  • Singleton pattern helps us to keep only one instance of a class at any time.
  • The purpose of singleton is to control object creation by keeping private constructor.

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:
//File Name: Singleton.java                                                                                  
    public class Singleton                                                                                                      
    {                                                                                                                              
         private static singleton ;
                                                                                                                               
        //A private constructor
         private Singleton(){  }                                                                             
        //Static Instance Method
        public static Singleton getInstance()
        {                                                                                    
           singleton=new Singleton();
            return singleton;
        }

      //Other method
       protected static void demoMethod()
       {  
       system.out.println("demomethod for singleton");
        }                      
  }                                                                                      
Here is the main program file where we will create singleton object:
//FileName :SingletonDemo.java
    public class SingletonDemo
    {            
        public static void main(String args[])
        {                                                              
            Singleton tmp=Singleton.getInstance();
            tmp.demoMethod();          
         }
    }
This would produce the following result:
demomethod for singleton







No comments: