设计模式-工厂方法
程序员文章站
2024-01-05 23:09:22
...
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);
}
}