teacher
Sign in

Factory

Hide which concrete class gets created behind a name or a subclass, and learn when a plain constructor is the better choice.

25 min4 interactive

The problem it solves

Code that says new SmsNotifier() is welded to that class. Sooner or later you see this:

  • An if / else chain on a type string, copied into five places.
  • Tests that cannot swap in a fake because the class is chosen inside the method.
  • A new channel that forces edits in every caller.

A factory moves the "which class?" decision into one place. Callers ask for something by name or role and receive an object that follows an interface (a contract listing methods, with no code).

1 of 7