定义:提供一个接口,用于创建一组相关的对象
在简单工厂模式和工厂模式中使用了炒饭的例子。现在依旧以这个例子介绍抽象工厂模式。
假设现在饭店已经开了无数家的分店,每个饭店使用的配菜的供应商以及配菜的处理工艺都需要针对当地做对应的调整。
在原来的设计中,只对炒饭的实例化做了对应的处理。现在不能笼统的处理炒饭,需要对配料配菜,比如,油,盐,米,酱油等也做对应的处理。如果对于每样的配料配菜沿用原来的模式,那可能会产生出,油工厂,盐工厂,米工厂。这样会导致类的数量一下子就多了很多。还好可以使用抽象工厂模式,把这些配料配菜看成是相关的一组对象,用一个工厂来生成。下面是示例代码:
public interface AbstactIngredientsFactory {
Oil getOil();
Rice getRice();
Salt getSalt();
}
public class NorthwestIngredientsFactory implements AbstactIngredientsFactory {
// 针对西北饭店的配料工厂
public Oil getOil() {
// 西北爱吃黄油
return new Butter();
}
public Rice getRice() {
// 长条米比较香
return new LongGrainRice();
}
public Salt getSalt() {
// 内陆应该多吃点高纳盐
return new HightSodium();
}
}
public class SoutheastIngredientsFactory implements AbstactIngredientsFactory {
// 针对东南饭店的配料工厂
public Oil getOil() {
// 花生油
return new PeanutOil();
}
public Rice getRice() {
// 长条米比较香
return new LongGrainRice();
}
public Salt getSalt() {
// 东南沿海还是吃低钠盐好点
return new LowSodium();
}
}
配料工厂准备好了,现在把它添加到炒饭里。
public class FriedRiceFactory {
AbstactIngredientsFactory ingredientsFactory;
public FriedRice getFriedRice(String type, AbstactIngredientsFactory ingredientsFactory) {
// 预留给子类决定要创建的对象
this.ingredientsFactory = ingredientsFactory;
}
public void prepare() {
Oil oil = ingredientsFactory.getOil();
Rice rice = ingredientsFactory.getRice();
Salt salt = ingredientsFactory.getSalt();
}
}
这里修改了工厂方法中的基类,通过配料工厂的接口来引用具体的配料工厂。那么在制作炒饭的时候,就不需要理会具体会使用到的是什么类型的配料了。
类似配料工厂这种,通过接口让子类实现一组相关的对象,并对外界屏蔽所有创建的细节的模式就是抽象工厂模式。