标签:
简单工厂模式:
-----------------------------------Pizza.java--------------------
package com;
public abstract class Pizza {
public abstract void prepare();
public abstract void bake();
public abstract void cut();
}
-----------------------------------APizza.java--------------------
package com;
public class APizza extends Pizza {
@Override
public void prepare() {
System.out.println("A prepare");
}
@Override
public void bake() {
System.out.println("A bake");
}
@Override
public void cut() {
System.out.println("A cut");
}
}
-----------------------------------BPizza.java--------------------
package com;
public class BPizza extends Pizza {
@Override
public void prepare() {
System.out.println("B prepare");
}
@Override
public void bake() {
System.out.println("B bake");
}
@Override
public void cut() {
System.out.println("B cut");
}
}
-----------------------------------CPizza.java--------------------
package com;
public class CPizza extends Pizza {
@Override
public void prepare() {
System.out.println("C prepare");
}
@Override
public void bake() {
System.out.println("C bake");
}
@Override
public void cut() {
System.out.println("C cut");
}
}
-----------------------------------SimplePizzaFactory.java--------------------
package com;
public class SimplePizzaFactory {
public Pizza createPizza(String type) {
if(type.equals("A")) {
return new APizza();
} else if(type.equals("B")) {
return new BPizza();
} else {
return new CPizza();
}
}
}
-----------------------------------PizzaStore.java--------------------
package com;
public class PizzaStore {
private SimplePizzaFactory simplePizzaFactory;
public PizzaStore(SimplePizzaFactory simplePizzaFactory) {
this.simplePizzaFactory = simplePizzaFactory;
}
public Pizza orderPizza(String type) {
Pizza pizza;
pizza = simplePizzaFactory.createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
return pizza;
}
// public static void main(String[]args) {
// PizzaStore pizzaStore = new PizzaStore(new SimplePizzaFactory());
// pizzaStore.orderPizza("A");
// }
}
分析:
工厂模式
Creater(创建者):PizzaStore
producter(产品):Pizza
抽象工厂模式:
针对接口编程
接口
总结:
-----抽象工厂的方法经常以工厂方法的方式实现。
-----抽象工厂的任务是定义一个负责创建一组产品的接口。这个接口内的每一个方法都负责创建一个具体产品。
-----我们利用实现抽象工厂的子类来提供这些具体的做法。
抽象工厂 VS 工厂方法
----抽象工厂针对接口编程
----工厂方法针对具体的实现类编程
标签:
原文地址:http://blog.csdn.net/u010919133/article/details/45622815