Skip to content

Design Patterns

Factory

Creating one object takes O(1) time (a constant amount, no matter how much you build). The real value is cleaner, centralized code.

The idea, in plain English

A factory is one function that builds an object for you. It decides which exact kind to build. Think of ordering 'a coffee' at a counter. You don't make it yourself — you say what you want, and the barista hands you the right drink.

How it works

  1. 1You call one function and tell it what kind of thing you want.
  2. 2That function makes the 'which type?' decision in one place.
  3. 3It builds and returns the right object. Your code never needs to know the details.

When you'd use it

Use this when building an object is complex, or the exact type depends on input. Keep that decision in one tidy spot instead of spreading it everywhere.

Common beginner mistakes

  • Don't let the factory grow into a giant tangle of if-statements. Split it up once it gets big.
  • Always add a sensible default for types you don't recognize.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
dog: Woof
cat: Meow
fish: ...

Not sure this is the right topic? See the learning paths → or where this leads →