Apr 25, 2017

Creational Design Patterns - Singleton

Singleton Pattern


Singleton pattern ensure that only one instance is initiating at the java virtual machine (JVM). That means only one object is created at the jvm and more then one object can't exist in jvm. This type of approach is used for use of resource like JDBC connections, files. JDBC connnection openning at on demand is high cost, so we should initiate jdbc connection onece. So lets see how to implement single pattern in java. So there are different ways to implement singleton in java. Based on the requirement you can choose what type of singleton pattern you should use.

Eager initialization

the instance of Singleton Class is created at the time of class loading. If we use this method, whather we use or not the object, object is created. it is not good. SO if we use the object at starting of the program use this approach. Let see how to implemnt this kind of singleton pattern

                            
public class SingletonEager {
    private static final SingletonEager instance = new SingletonEager();
    //private constructor to avoid client applications to use constructor
    private SingletonEager(){}
          public static SingletonEager getInstance(){
             return instance;
          }
    }
                            
                        

Here there is a private static variable it get initiated at the startup of the program. Becase static variables are created at the class loading

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.