Simple Factory

One of the main idea about modern Object Oriented Design is that we should tend to refer to interfaces instead of concrete classes. This leads the design to be as flexible as possible. But using the new operator drives us necessary in the opposite direction.

So, instead of using directly the new operator is often better to delegate the actual creation of an object to a specific functionality. This is showed by the Factory Pattern. In chapter four of
Head First Design Patterns
we are introduced to three different Factory Patterns.

In this post I'm about to talk about the first of them, a basic, stripped down, version aptly dubbed Simple Factory. It is so simple that it is often considered more a programming idiom than a pattern.

Let's ponder over this code, were a pizza is created:
Pizza order() {
   Pizza pizza = new Pizza();

   pizza.prepare();
   pizza.bake();
   pizza.cut();
   pizza.box();
   return pizza;
}
Aiming at some generalization, we could allow the user to create different types of pizza:
Pizza order(String type) {
   Pizza pizza;
   if(type.equals("cheese"))
      pizza = new PizzaCheese();
   else // ...

   // ...
   return pizza;
}
The code is getting messy. It looks natural to grab all the code related to the pizza creation and move it a specific place, that could be called anytime we want to generate a new pizza. And so that is our first factory:
public class SimplePizzaFactory {
   public Pizza create(String type) {
      Pizza pizza = null;

      if(type.equals("cheese"))
         pizza = new PizzaCheese();
      else // ...

      return pizza;
   }
}

We simply moved the code for generating pizzas in a dedicated class. The create() method could be static, and in this case we should not actually create an instance of the class for using it. But this bonus comes at the price of losing the chance of creating a derived class and so changing the method behavior.

No comments:

Post a Comment