Factory: Factory Method and Abstract Factory

A factory creates objects for you, so the calling code asks for 'a notifier' without knowing which concrete class gets built.

Why it matters

If the code that uses an object also decides which concrete class to create, every new type means editing that code in many places.

The idea

Factory Method: one method decides which class to create. Abstract Factory: creates whole families of related objects that must match, such as all dark-theme or all light-theme UI parts. Both keep 'new ConcreteClass()' in one place.

Ordering from a car factory: you ask for 'a family car', and the factory decides the exact model and parts.

A car factory has a fixed catalogue. If every new type means editing one big if/else inside the factory, you've just moved the problem. A registry of creators keeps it open for extension.

How it works

  1. Define a common interface: Notifier with send(message).
  2. Implement it in EmailNotifier, SmsNotifier and PushNotifier.
  3. Put the 'which class?' decision in one factory, using a dictionary from name to class.
  4. Callers ask the factory for 'sms' and use the result only through the interface.
  5. Adding a WhatsAppNotifier means one new class and one new dictionary entry.

Example

NotifierFactory.create('sms') returns an SmsNotifier, and the order service just calls notifier.send().

Key points

Common mistakes

Not true: A factory written as one long if/else is easy to extend with new types.
In fact: Every new type then means editing that same if/else. A registry (a dictionary from a name to a class) lets a new type be added without touching the factory.

In the interview

A factory centralises object creation: callers ask for a type by name or configuration and get an object behind a common interface, so adding a new type doesn't change the calling code. Abstract Factory extends this to whole families of matching objects.

Part of Unit 6: Design patterns in the free System Design course.