Created
August 31, 2012 19:12
-
-
Save lucasdavila/3557618 to your computer and use it in GitHub Desktop.
Factory pattern or "convention over ifs"?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example from book "Head First Design Patterns". | |
// without factory pattern | |
public class PizzaStore { | |
public Pizza orderPizza(String type) { | |
Pizza pizza; | |
// bad! we have a lot of ifs here... | |
if (type.equals("cheese")) { | |
pizza = new CheesePizza(); | |
} else if (type.equals("pepperoni")) { | |
pizza = new PepperoniPizza(); | |
} else if (type.equals("clam")) { | |
pizza = new ClamPizza(); | |
} else if (type.equals("veggie")) { | |
pizza = new VeggiePizza(); | |
} | |
pizza.prepare(); | |
pizza.bake(); | |
pizza.cut(); | |
pizza.box(); | |
return pizza; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example from book "Head First Design Patterns". | |
public class PizzaStore { | |
SimplePizzaFactory factory; | |
public PizzaStore(SimplePizzaFactory factory) { | |
this.factory = factory; | |
} | |
public Pizza orderPizza(String type) { | |
Pizza pizza; | |
// good! (or bad?) now we have another class to decide what pizza should be created... | |
pizza = factory.createPizza(type); | |
pizza.prepare(); | |
pizza.bake(); | |
pizza.cut(); | |
pizza.box(); | |
return pizza; | |
} | |
} | |
public class SimplePizzaFactory { | |
public Pizza createPizza(String type) { | |
Pizza pizza = null; | |
// Oh ok! But we still having many ifs... Is it good? | |
if (type.equals("cheese")) { | |
pizza = new CheesePizza(); | |
} else if (type.equals("pepperoni")) { | |
pizza = new PepperoniPizza(); | |
} else if (type.equals("clam")) { | |
pizza = new ClamPizza(); | |
} else if (type.equals("veggie")) { | |
pizza = new VeggiePizza(); | |
} | |
return pizza; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PizzaStore | |
def order_pizza pizza_type | |
# and what happens if I decide to use some "convention over ifs" here? It's a good or bad idea? | |
pizza = eval(pizza_type.constantize).new | |
pizza.prepare | |
pizza.bake | |
pizza.cut | |
pizza.box | |
pizza | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment