Head First Design Patterns Series / 4 (The Factory Pattern: Baking with OO Goodness)

Building Extensible & Maintainable Object Oriented Software

Merve Arslan
Odeal-Tech
2 min readJan 30, 2023

--

The Factory Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate.

Encapsulating object creation

In this chapter, the authors explain through a pizza shop sample. As a result of the need for more than one type of pizza, they first start by separating the things that varying and the things that don’t. Then they resort to the encapsulation method.

The orderPizza() method has a well-honed order system. The things that change are the styles demanded by region. So we will collect all these variations under the createPizza() method and hold it responsible for creating the right type of pizza.

After defining the creator classes, let’s define the products and take a look at the final classes we tried to make with the factory pattern.

The Dependency Inversion Principle

In previous chapters, the authors mentioned that reducing dependencies on concrete classes makes code better.

This design principle is that our high-level components do not depend on our lower-level components; instead, it suggests that both should depend on abstractions.

When we adapt this design principle to the PizzaStore example and examine it on the diagram, the change is as follows.

Before :

After Applying the Principle:

--

--