设计模式-工厂方法


public abstract class PizzaStore {

public void orderPizza(String type) {

Pizza pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();

}

public abstract Pizza createPizza(String type);
}


public abstract class Pizza {

public abstract void prepare();
public abstract void bake();
public abstract void cut();
public abstract void box();

}


public class NYPizzaStore extends PizzaStore {

@Override
public Pizza createPizza(String type) {
if ("cheese".equals(type)) {
return new NYStyleCheesePizza();
} else if ("veggie".equals(type)) {
return new NYStyleVeggiePizza();
}
return null;
}

}


public class ChicagoPizzaStore extends PizzaStore {

@Override
public Pizza createPizza(String type) {
// TODO Auto-generated method stub
return null;
}

}


public class NYStyleCheesePizza extends Pizza {

@Override
public void prepare() {
// TODO Auto-generated method stub

}

@Override
public void bake() {
// TODO Auto-generated method stub

}

@Override
public void cut() {
// TODO Auto-generated method stub

}

@Override
public void box() {
// TODO Auto-generated method stub

}

}


public class NYStyleVeggiePizza extends Pizza {

@Override
public void prepare() {
// TODO Auto-generated method stub

}

@Override
public void bake() {
// TODO Auto-generated method stub

}

@Override
public void cut() {
// TODO Auto-generated method stub

}

@Override
public void box() {
// TODO Auto-generated method stub

}

}



public class BaseGenerator<T> implements Generator<T> {

private Class<T> type;

public BaseGenerator(Class<T> type) {
this.type = type;
}

@Override
public T next() {
try {
return type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 泛型类型对静态函数不管用,在此还需要为该函数声明类型
public static <T> Generator<T> create(Class<T> type) {
return new BaseGenerator<T>(type);
}
// 对非静态的可直接使用
public Generator<T> create1(Class<T> type) {
return new BaseGenerator<T>(type);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值