抽象工厂模式是什么?
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指明具体类。
抽象工厂模式解决什么问题?
榨果汁需要原材料,材料可能来自全国各地:
class Apple {
String name;
}
class GuangdongApple extends Apple {
public GuangdongApple() {
name = "广东苹果";
}
}
class HainanApple extends Apple {
public HainanApple() {
name = "海南苹果";
}
}
public class Juice {
Apple apple;
Juice(Apple apple) {
this.apple = apple;
}
public void appleJuice() {
System.out.println("正在榨" + apple.name);
}
}
生产过程:
Apple a=new GuangdongApple();
Juice juice=new juice(a);
juice.appleJuice();
- problem1:当需要榨Banana时,需要修改juice源代码增加bananaJuice()方法并设置相关属性
- problem2:当产地(新疆、北京)越来越多时,类变多且难以维护
抽象工厂模式实现
创建原料工厂接口,如果增加了原料(Banana),可以直接添加:
interface IngredientFactory {
public Apple createApple();
}
创建不同的原料工厂(广东、海南)用于生产不同地域的原料(将类进行归类):
class GuangdongIngredientFactory implements IngredientFactory {
@Override
public Apple createApple() {
return new GuangdongApple();
}
}
class HainanIngredientFactory implements IngredientFactory {
@Override
public Apple createApple() {
return new HainanApple();
}
}
将Juice抽象,内部维护原料工厂接口,把Juicing()方法推迟到子类实现:
abstract public class Juice {
IngredientFactory ingredientFactory;
abstract void Juicing();
}
创建AppleJuice,根据不同的工厂原料榨汁:
class AppleJuice extends Juice {
public AppleJuice(IngredientFactory ingredientFactory) {
this.ingredientFactory = ingredientFactory;
}
@Override
void Juicing() {
System.out.println("正在榨" + ingredientFactory.createApple().name);
}
}
生产过程:
IngredientFactory factory=new GuangdongIngredientFactory();
Juice juice=new AppleJuice(factory);
juice.Juicing();