dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

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.

 

 

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