Chapter 3. The Factory Pattern

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

How a Factory Works

To understand the Simple Factory pattern, let's look at the diagram in Figure 3.1.

Figure 3.1. A Simple Factory pattern.

In this figure, X is base class and ...

Get Java™ Design Patterns: A Tutorial 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.