Factory Method Pattern - Misconception

This post does not talk about the Factory Method Pattern, but I would like to discuss about from where it starts.
Recently I had the privilege to attend a training on the topic. I do not miss opportunity to attend any session on process or pattern, you always have something to learn.
It was an good interactive session but we had the same old discussion that instead getting to the factory method we ended up discussing the implementation (some may call it simple factory idom, but i dont) forgetting that patterns only talk about the behavior and interaction and not about implementation.

Let me take a chance to explain the Factory Method
Factory Method -I will use the common example of PizzaFactory as used by Head First to explain the factory method:
Elements: Pizza (Product)
SimplePizzaFactory (Creator)












Definition: The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."

This is a definition I extracted from Wikipedia. If you read it carefully it says that subclass decides which class to instantiates and not how it instantiates. But most of the time in discussions and trainings we see the following example and end up discussing the implementation:

class SimplePizzaFactory {
    public enum PizzaType {
        HamMushroom,
        Deluxe,
        Hawaiian
    }
      public static Pizza createPizza(PizzaType pizzaType) {
        switch (pizzaType) {
            case HamMushroom:
                return new HamAndMushroomPizza();
            case Deluxe:
                return new DeluxePizza();
            case Hawaiian:
                return new HawaiianPizza();
        }
        throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
    }
}

In the above example the important fact is that
SimplePizzaFactory is a creator with createPizza() being the factory method returning the type of pizza and thats where it should end but we end up discussing the implementation as if it is part of the pattern. Important part to note here is that SimplePizzaFactory is a concrete creator and in this example we do not have a abstract creator.
I am not sure how much i would have made sense. Please do let me know if I am wrong or may need to change the speech.
Thanks for reading........



Comments

Popular posts from this blog

Hibernate: a different object with the same identifier value was already associated with the session

BeanDefinitionStoreException: Failed to parse configuration class: Could not find class [javax.jms.ConnectionFactory]