Singleton, factory, and observer are reusable design patterns for common object-oriented problems. Singleton restricts a class to one instance, factory centralizes object creation, and observer notifies dependent objects when a subject changes state.
How the Patterns Work
| Pattern | Mechanism | Typical use |
|---|---|---|
| Singleton | A private constructor, one class-level instance, and a public access method return that instance. | A shared logger, configuration manager, or controller. |
| Factory | A factory method chooses and returns a concrete object through a common interface. | Creating Document, Enemy, or Payment objects from an input. |
| Observer | A subject stores observers and calls each update method after a state change. | Notifications, event systems, or synchronized user-interface components. |
A singleton's access method checks whether an instance exists. It creates one only when necessary; otherwise, it returns the existing instance. This controls shared access, although overuse can introduce hidden dependencies.
A factory separates object creation from object use. Client code can call createShape("circle"); the factory returns a Circle, while the client depends on the Shape interface. New concrete classes can therefore be added with fewer client-code changes.
In the observer pattern, the subject provides attach, detach, and notify operations. Each observer implements a common update operation, establishing a one-to-many dependency while reducing direct coupling between subject and dependants.
A common misconception is that a singleton is merely a global variable. Unlike an unrestricted global, it controls its own instantiation and access. A factory also need not be a separate class; it may be a factory method.
IB Exam Technique
For B3.2 HL questions, identify the problem solved, participating classes, and flow of control. In an explain response, do not merely name the pattern: show how its mechanism supports encapsulation, polymorphism, or reduced coupling in the scenario. Use scenario-specific class names to demonstrate application rather than memorized definitions.