Singleton
Line 17: | Line 17: | ||
The Singleton pattern can be used in the [[Abstract Factory]] pattern. | The Singleton pattern can be used in the [[Abstract Factory]] pattern. | ||
+ | |||
+ | == Recognising the pattern == | ||
+ | |||
+ | '''Classes:''' ''Singleton''. | ||
+ | * private constructor. | ||
+ | * private static attribute to hold uniqueInstance of itself. | ||
+ | * concrete public static getInstance() method. | ||
== See also == | == See also == |
Revision as of 22:44, 4 October 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.
Recognising the pattern
Classes: Singleton.
- private constructor.
- private static attribute to hold uniqueInstance of itself.
- concrete public static getInstance() method.