Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Sep 23, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Create a Single Instance of an Object

There are situations when you need to insure that only a single instance of an object is created in a program. Examples of this include a connection to a database system, a lock manager in a server program, and so on. This code shows you how to implement the "Singleton" design pattern in Java. This particular implementation includes lazy instantiation:

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();

Randy Kahle
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date