工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
举个实例:
比萨店加盟:一般披萨点餐需要经过制造,准备,打包等一系列步骤,现在有两个加盟店,工序都差不多,但是生产不同的比萨,在口味等方面有一定区别。
如何用工厂模式实现这个例子:
PizzaStore:
public abstract class PizzaStore {
public Pizza orderPizza(String type)
{
Pizza pizza;
pizza =createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
protected abstract Pizza createPizza(String type);
}
类NYPIZZASTORE:
public class NYPizzaStore extends PizzaStore {
public Pizza createPizza(String item){
if(item.equals("cheese")){
return new NYStyleCheesePizza();
}else if(item.equals("veggie"))
{
return new NYStyleVeggizPizza();
}else{
return null;
}
}
}
类Pizza:
import java.util.ArrayList;
public abstract class Pizza {
void prepare()
{
System.out.println("Pizza is prearing");
}
void bake()
{
System.out.println("Bake for 25 mins");
}
void cut(){
System.out.println("Cutting into slices");
}
void box(){
System.out.println("Pizza in box");
}
}
类
public class NYStyleCheesePizza extends Pizza{
}
类:
public class NYStyleVeggizPizza extends Pizza {
}
public class PizzaTestDrive {
public static void main(String[] args)
{
PizzaStore nyStore = new NYPizzaStore();
Pizza pizza = nyStore.orderPizza("cheese");
}
}