`
frank127
  • 浏览: 10533 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

factory pattern

阅读更多
let's say you have a pizza shop. you might end up writing some code like this:

Pizza orderPizza() {
Pizza pizza = new Pizza();
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;


When you need more than one type of pizza

Pizza orderPizza(String type) {
Pizza pizza;
if (type.equals("cheese")) {
 pizza = new CheesePizza();
} else if (type.equals("greek")) {
 pizza = new GreekPizza();
} else if (type.equals("peoperoni")) {
 pizza = new PepperoniPizza();
}
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;


Clearly, dealing with which concrete class is instantiated is really messing up our orderPizza() method and preventing it from being closed for modification


What should we do then?
Well, what we're going to do is take the creation code and move it out into another object that is only going to be concerned with creating pizzas.

We've got a name for this new object: we call it a factory.


Reworking the pizzastore class
public class PizzaStore {
 SimplePizzaFactory factory;

 public PizzaStore(SimplePizzaFactory factory) {
  this.factory=factory;
 }
 
 public Pizza orderPizza(String type) {
  Pizza pizza;
  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;
    
    if (type.equals("cheese")) {
      pizza=new CheesePizza();
    } else if (type.equals("pepperoni")) {
      pizza=new PepperoniPizza();
    } else if (type.equals("veggie")) {
      pizza=new VeggiePizza();
    }
    return pizza;
}
}


class diagram


Franchising the pizza store
As the franchiser, you want to ensure the quality of the franchise operations. Each franchise might want to offer different styles of pizzas(NY, Chicago) depending on where the franchise store is located and the tastes of the local pizza connoisseurs

NyPizzaFactory nyFactory=new NYPizzaFactory();
PizzaStore nyStore=new PizzaStore(nyFactory);
nyStore.order("Veggie");


So you test marketed the SimpleFactory idea, and what you found was that the franchise were using your factory to create pizzas. Rethinking the problem a bit, you see that what you'd really like to do is create a framework that ties the store and the pizza creation together, yet still allows things to remain flexible.



allowing the subclasses to decide


Let's make a PizzaStore

public class NYPizzaStore extends PizzaStore {
  Pizza createPizza(String item) {
    if (item.equals("cheese")) {
      return new NYStyleCheesePizza();
    } else if (item.equals("veggie")) {  
      return new NYStyleVeggiePizza();
    } else return null;
  }
}
分享到:
评论
1 楼 az12xc34 2014-12-01  

相关推荐

Global site tag (gtag.js) - Google Analytics