5

The Factory Pattern

One type of pattern that we see again and again in OO programs is the Simple Factory pattern or class. A Simple Factory pattern returns an instance of one of several possible classes, depending on the data provided to it. Usually all the classes it returns have a common parent class and common methods, but each one performs a task differently and is optimized for different kinds of data. This Simple Factory is not one of the 23 GoF patterns, but it serves here as an introduction to the somewhat more subtle Factory Method GoF pattern we’ll discuss shortly.

How a Factory Works

Let’s consider a simple case where we could use a Factory class. Suppose we have an entry form and want to allow users to enter their names either ...

Get Python Programming with Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.