Card 02/ 09
Singleton Pattern Structure: The Class Diagram
One class, a private constructor, a static field holding the instance, and a static method returning it.
Singleton has one participant, the singleton class, and three parts inside it that work together: a constructor that no other class may call, a static field that holds the one instance, and a static method that creates the instance on first use and returns it. This card reads those parts off the smallest class diagram in the Gang of Four's catalogue.
| Part | Role |
|---|---|
-Singleton() | A private constructor, so no code outside the class can create a second instance. |
-instance | A static, private field, underlined in the diagram, holding the one instance once it exists. |
+get_instance() | A static, public method: it creates the instance if the field is empty and returns the field. |
+operation() | The class's real work, called on the instance like any other method. |
In UML, an underlined member is static: it belongs to the class rather than to any one object, which is why a client can call get_instance() before any instance exists. The minus signs mark private members, and a private constructor is what turns "should have one instance" into "can have only one".
Creating the instance inside get_instance(), on the first call, is called lazy initialisation: if nothing ever asks for the instance, it is never created. The alternative, creating it when the class loads, is simpler and safe with threads, at the cost of creating it even when it is not needed. The template shows both.
← → move through sections and cards