Skip to content

Instantly share code, notes, and snippets.

@lucasdavila
Created August 31, 2012 19:12
Show Gist options
  • Save lucasdavila/3557618 to your computer and use it in GitHub Desktop.
Save lucasdavila/3557618 to your computer and use it in GitHub Desktop.
Factory pattern or "convention over ifs"?
// 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;
}
}
// 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;
}
}
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