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 only one should create a new one. The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated. A Java programming language solution is as follows (based on the Q&A link, modified for multi-threading):
  public class Singleton {      private static Singleton INSTANCE = null;        // Private constructor suppresses       // default public constructor      private Singleton() {}        //synchronized creator to defend against multi-threading issues      //another if check here to avoid multiple instantiation      private synchronized static void createInstance() {          if (INSTANCE == null){               INSTANCE = new Singleton();          }      }        public static Singleton getInstance() {          if (INSTANCE == null) createInstance();          return INSTANCE;      }  } 
A possible C++ solution (also known as Meyers singleton) where the singleton is a static local object (note: this solution is not thread-safe and is designed to give an idea of how singletons work rather than a solution usable in large-scale software project).
  template class Singleton  {      public:      static T& Instance()      {          static T theSingleInstance; //assumes T has a default constructor          return theSingleInstance;      }  }; 
  class OnlyOne : public Singleton  {      //..rest of interface defined here  }; 

See also

External links

 

<< PreviousWord BrowserNext >>
baloch
factsheet five
cassette culture
christian democratic appeal
skin cancer
lodi, italy
kaiju
gamera
the big u
sasquatch
shub niggurath
damselfly
oz
billi 99
swamp thing
william hope hodgson
adapter pattern
hms sidon
dll
facade pattern
versatackle knot
george mcfarland
bridge pattern
tire
muskeg
asia carrera
list of children's literature authors
portable executable
lee kuan yew
list of playwrights
monster
beetle (disambiguation)
triticale
brian froud
pika
ida rentoul outhwaite
richard dadd
cicely mary barker
thomas the rhymer
germanic
great ocean road
guangdong
li ao
poplog