Introduction to: Patterns of Design (III)

If you search this words on google, factory vs builder pattern, you will find thousands of web pages which try to explain the difference between this two patterns.

We could say that the main difference between them, is the type of complexity in creating the product. So, when the product must be created step-by-step, you’d rather use the Builder Pattern. Otherwise, when the product is created in a single action, the Factory Method must be¬†chosen. In this post, we will focus on this last pattern.

Class Diagram for the Factory Method Pattern

The purpose of Factory Method Pattern is to decouple the concrete products from the client, which will be only coupled with an interface of Product. As it can be seen, this pattern is useful when there is a hierarchy of Product.

Actually, a client must only know about the Product interface and the Creator abstract class. He is isolated from the concrete implementations of both Creator and Product.

Now we will see a situation where this pattern could be applied. We need to model a Soda Factory. This factory (Creator abstract class) produces different kinds of soda (soda is the interface, and each kind of it is a concrete class). The Creator is not supposed to know about any kind of soda. Each concrete class, extending Creator, will override the FactoryMethod and will produce an implementation of Product interface. The clients of this model, will know that there is a Creator and a Product interface, but they don’t care about the concrete classes. When using Factory Method pattern, from the client’s point of view, the Product is created as a result of invoking only one method. On the other hand, when the Builder Pattern is used, the creation is made step-by-step.

This table summary may help.

Builder Pattern Factory Method Pattern
There is no hierarchy of Products (or it’s very simple) There is a hierarchy of Products
Products are created step-by-step Products are created only in one step
Subclasses of Builder know about steps of creation Subclasses of Creator will create a concrete type of Product
The creation steps are very clear The creation algorithm may differ from one type of Product to another