Singleton

From CSSEMediaWiki
Revision as of 01:40, 19 September 2008 by Elliot Fisher (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Singleton is a simple design pattern to ensure that only one instance of a class can exist, and provide an easy, global way to access it. Some classes in a domain should only ever have one instance, for example a Printer Spooler class that handles print requests and sends them to Printers. A global variable could be used, but this is bad design and doesn't stop multiple instances being created.

The Singleton pattern makes the class itself responsible for ensuring only one instance exists.

Contents

Use when

  • There must be only one instance of a class and it must be easily accessible to clients.
  • When the class needs to be extensible, and clients should be able to use a derived class without changing their code.

Structure

SingletonStructure.png

Singleton defines an instance() method through which clients can access the unique instance. If an instance doesn't exist, it creates one before returning it. The constructor is private, ensuring only one instance can be created.

Note

The Singleton pattern can be used in the Abstract Factory pattern.

See also

Personal tools