devxlogo

Create a Single Instance of an Object

Create a Single Instance of an Object

There are situations when you need to insure that only a single instanceof an object is created in a program. Examples of this include aconnection to a database system, a lock manager in a server program,and so on. This code shows you how to implement the “Singleton” designpattern in Java. This particular implementation includes lazyinstantiation:

 public class SingleInstance     {     // Java guarantees that si is set to null     private static SingleInstance si;     // declare the constructor to be private so that no     // one can create an instance of this class except the class itself     private SingleInstance() {}     // This static method will return a reference to     // the same instance no matter how many times it is called.     public static SingleInstance getSingleInstance()         {         // si will be null the first time this is called.         if ( null == si )             {             si = new SingleInstance();             }         return si;         }     }

To get an instance of this class, use the static method of the class:

 SingleInstance i = SingleInstance.getSingleInstance();

devx-admin

Share the Post: