工厂模式
工厂模式是创建对象的一种方法,它把客户端和创建对象解耦合开来。工厂模式又分为工厂方法和抽象工厂模式。
工厂方法又被称之为简单工厂模式,严格来说这是一个良好的编程习惯,而不是设计模式,使用工厂方法也可以把客户端和创建对象解耦。工厂方法面向的是对象,通常的做法是创建一个抽象类,包含一个创建对象的抽象方法,把具体创建对象的权限交予子类,由子类去决定创建什么对象。
public abstract class PizzaStore {
abstract Pizza createPizza(String type);
public Pizza orderPizza(String type){
Pizza pizza = createPizza(type);
pizza.produce();
return pizza;
}
}
public class NyPizzaStore extends PizzaStore{
@Override
Pizza createPizza(String type) {
if ("cheese".equals(type))
return new NyChessePizza();
if ("veggie".equals(type))
return new NyVeggiePizza();
return null;
}
}
public interface Pizza {
void produce();
}
public class NyChessePizza implements Pizza {
@Override
public void produce() {
}
}
public class NyVeggiePizza implements Pizza {
@Override
public void produce() {
}
}
抽象工厂模式可以把产品族联合起来,通常做法是定义一个工厂接口,一个产品接口,由工厂接口的子类创建对象。客户端只需要依赖工厂的抽象,高层依赖抽象,低层也依赖抽象。
PizzaStore为客户端调用 ,使用组合注入PizzaFactory.可以看到只依赖于接口,而NyPizzaFatory为具体创建对象,这是必须得依赖于具体的。依赖于抽象,不要依赖于具体,除了NyPizzaFatory,高层组件和低层组件都遵循这个原则。这是依赖倒置。
public interface Pizza {
void produce();
}
public interface PizzaFatory {
public Pizza createPizza(String type);
}
public class VeggiePizza implements Pizza {
@Override
public void produce() {
System.out.println("VeggiePizza produce");
}
}
public class PeppersonPizza implements Pizza {
@Override
public void produce() {
System.out.println("PeppersonPizza produce");
}
}
public class NyPizzaFatory implements PizzaFatory {
public Pizza createPizza(String type){
if ("chesse".equals(type))
return new CheesePizza();
if ("pepperson".equals(type))
return new PeppersonPizza();
if ("Veggie".equals(type))
return new VeggiePizza();
return null;
}
}
public class PizzaStroe {
private PizzaFatory pizzaFatory;
public PizzaStroe(PizzaFatory pizzaFatory) {
this.pizzaFatory = pizzaFatory;
}
public Pizza orderPizza(String type){
Pizza pizza = pizzaFatory.createPizza(type);
pizza.produce();
return pizza;
}
}