dimanche 1 novembre 2015

Make factory method more dynamic

I am implementing the factory pattern in my code, so came across one interesting thing in factory that I can replace the if else condition in the factory method with Reflection to make my code more dynamic.

Below is the code for both the designs......

1) With if-else conditions

   public static Pizza createPizza(String type) {

        Pizza pizza = null;

        for(PizzaType value : PizzaType.values())
        {
            if(type.equals(PizzaType.Cheese))
            {
                pizza = new CheesePizza();
            }

            else if (type.equals(PizzaType.Tomato))
            {
                pizza = new TomatoPizza();
            }

            else if (type.equals(PizzaType.Capsicum))
            {
                pizza = new CapsicumPizza();
            }
            else
            {
                try {
                    throw new Exception("Entered PizzaType is not Valid");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return pizza;
    }

2) With Reflection

    public static Pizza createPizza(String type) {

            Pizza pizza = null;

            for(PizzaType value : PizzaType.values())
            {
                if(type.equals(value.getPizzaTypeValue()))
                {
                    String fullyQualifiedclassname = value.getClassNameByPizzaType(type);

                    try {
                        pizza = (Pizza)Class.forName(fullyQualifiedclassname).newInstance();
                    } catch (InstantiationException | IllegalAccessException
                            | ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            return pizza;
        }

Second way looks very good to me as I can make my code more dynamic by using it, as I can create one property file with the names of classes and type associated with it to serve the Open and close a bit more, as if in future owners wants to add more pizzas to PizzaStore then he would just make the entry in the property file and will just create one more subclass of Pizza.

But I read that reflection has many disadvantages mentioned few of them.

It is hack of compiler
Automatic development tools are not able to work with reflections code
It's difficult to debug reflections code
Reflection complicates understanding and navigation in code
Significant performance penalty

So very curious to know that, which design is good, as I am very interested to make my code more and more dynamic.

Aucun commentaire:

Enregistrer un commentaire