The goal of the simple factory idiom is to separate the process of creating concrete objects to reduce the dependency of the client from the concrete implementations.
To implement the simple factory we need three things:
- A factory, the pizza factory.
- The products the factory makes which are the pizza objects.
- The client that uses the factory, which is the pizza store.
So, let’s take our pizza creation code, encapsulate it, separate it. And we’ll encapsulate it in a class called Factory.
Why a Factory? Because this is a class whose sole responsibility is creating pizzas — it’s a pizza factory.
To do that we’re going to take this conditional code for creating pizzas and put it into a separate class, in a method name createPizza. Each time we want a pizza, we’ll call the method, pass it a type, and the method will make a pizza for us and return an object that implements the pizza interface.
Now all this creation will be in a separate class, nicely separated form the restaurant code. So, let’s integrate this with our client code or restaurant code. Let’s assume that we’ve created a factory object already. And call it to create the pizza, passing it the type variable.
Our order pizza method no longer has to worry about the concrete type of the pizza. It could be a veggie pizza, a cheese pizza, or a pizza we haven’t even heard of yet. We know whatever type gets returned by the factory, it implements the pizza interface. And that’s all we care about.
So we call this object design the simple factory idiom. The simple factory idiom allows us to decouple the process of creating objects from the client that uses those objects. Our pizza store used a simple factory to create pizzas, so that the pizza store doesn’t have to worry about the details of the various pizza types. The factory deals with that. While the pizza store focuses on getting the pizza ready for the customer.
We start we the client of the restaurant, the pizza store. And then we have our factory. The factory is the only place the concrete types of pizzas are known. And then we have the products, what the factory makes or pizzas, and there could be many concrete types of those.
To generalize this a bit, we could look at the same diagram without pizzas.
And here we have the client, a factory, and a set of products that implement a common interface.
Now, one thing to note. This is not a full fledged official pattern. It is more of an idiom that’s commonly used. That said it is the first step to understanding some of the more common design patterns.
And now we’ll put everything together in a main class called the pizza test drive which will create a pizza store and use it to create pizzas.
Freeman, Eric, and Elisabeth Freeman. “Chapter 4. The Factory Method Pattern: Baking with OO Goodness.” Head First Design Patterns. Sebastopol, CA: O’Reilly Media, 2005. N. pag. Print