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();
See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist