← Design Patterns learning path
Design Patterns · Module 2 of 10

Singleton and Factory

Control object creation.

📖 Key ideas

  1. Singleton ensures a class has only one instance with global access.
  2. Used for configuration, logging, connection pools (carefully).
  3. Factory Method lets subclasses decide which object to create.
  4. Simple factory: a method returns the right object based on input.
  5. Factories hide creation details from callers.
💡 Real-life example: A factory is a vending machine: press "tea" or "coffee" and get the right drink without knowing how it's made.
SingletonOnly one instance
Factory MethodSubclasses decide object creation
Simple factoryMethod returning objects by type
Lazy initialisationCreate when first needed