Design Patterns

Factory Pattern

The Factory Pattern explained: one place to create objects so callers never pick the class, with Python examples, Factory Method, Abstract Factory and pitfalls.

  • 5 min read
  • 5 questions
  • +35 XP
Transcript

Factory pattern explained by cats. Kitty wants a toy, but Kitty doesn't make toys. Kitty just asks for one. There's a toy factory. Kitty says ball. Factory gives a ball. Kitty says mouse. Factory gives a mouse. Kitty says feather.

Factory gives a feather. Kitty doesn't care how the toy is built. She just gets the toy she asked for. That's the factory pattern. One place to create many kinds of objects. Perfect when you don't want to hard code object creation everywhere.

In code, Kitty calls the factory method. Factory decides which class to instantiate. Kitty gets back a ready -to -use object, ball, mouse, or feather. That's factory pattern.