Singleton
(New page: 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...) |
|||
Line 12: | Line 12: | ||
[[image: SingletonStructure.png]] | [[image: 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. | + | 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. The $ signs mean "static." |
== Note == | == Note == |
Revision as of 01:41, 19 September 2008
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
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. The $ signs mean "static."
Note
The Singleton pattern can be used in the Abstract Factory pattern.