Teach Time Encyclopedia - Learn About Our World
Home Page
Teach Time
Featured Topics

United States
by state

CITYology

Academic Disciplines

Historical Timelines

Themed Timelines

Calendars

Reference Tables

Biographies

How-tos



Monday, October 13, 2008

Singleton pattern

In computer science, the singleton design pattern is designed to restrict instantiation of a class to one (or a few) objects. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.

The singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If one does exist it returns a reference to the object that already exists. To make sure that the object cannot be instantiated any other way the constructor is made either private or protected.

The singleton pattern must be carefully constructed in multi-threaded applications. If both threads execute the creation method at the same time when a singleton does not yet exist, they both do a check for an instance of the singleton and then both create a new one.

The classic solution to this problem is to use mutual exclusion on the data that indicates that the object is already instantiated.

A Java programming language solution is as follows (see the Q&A link in external links):

public class Singleton {

   private static final Singleton INSTANCE = new Singleton();

// Private constructor suppresses // default public constructor private Singleton() {}

public static Singleton getInstance() { return INSTANCE; } }

A possible C++ solution where the singleton is a static local object:

template class Singleton {

public:

 static T& Instance()
 {
    if(!m_instance)
    {
       static T theSingleInstance;
       m_instance = &theSingleInstance;
    }
    return *m_instance;
 }
private:
 static T* m_instance;
};

class OnlyOne : public Singleton {

 //..rest of interface defined here
};

External Links



Internet Hotel Solutions

Site Sponsors
AC Units
Baltimore Harbor
Boot Camp Grads
Bra Size
Burkittsville
College Hotels
Digital Harbor
Free Cell Phones
Golden Hare Travel
Golf Vacations
Golf Courses
Gourmet
Hair Styles
Hippodrome
iWoman
Lesson Plans
Maryland Hotels
MD Genealogy
Minor League Stuff
Motel Site
Ocean City
OC Real Estate
Old Agers
Office Supplies
Orlando
Pet Friendly Hotel
Room Prices
Savannah, GA
Ski Vacations
South Baltimore
Student Teaching
Travel Sources
University Hotels
Visit Military Bases
Washington, DC

Brought to you by NoChildLeftBehind.com and the Beaches and Towns Network, LLC.