概念:为创建一组相关或相互依赖的对象提供一个接口,而且无须指定他们的具体类。
抽象工厂模式是工厂方法模式的升级版本。在存在多个业务品种或分类时,抽象工厂模式是一种更好的解决方式。
抽象工厂模式的UML类图如下:
可以看出来,和工厂方法模式最大的区别就是支持了更多的产品线。还是通过一个例子来帮助大家理解这个过程。假设一辆车的生产过程只有车架、引擎和轮胎这三个步骤。我们创建这三个接口,对应UML图中的ProductA和ProductB,当然这里是三种产品,也可以更多。然后生产奔驰和宝马两个产品线,即创建6个类,奔驰车的车架、引擎和轮胎,宝马车的车架、引擎和轮胎,分别继承自车架、引擎和轮胎接口。然后在工厂类这边,我们创建一个带有3个方法的接口,分别是创建车架、创建引擎、创建轮胎。这样一来,我们的两个实现类(奔驰生产工厂和宝马生产工厂)就可以分别有一条生产汽车的流水线了。然后我们看代码。
public interface CarFrame {void getCarFrame();
}public class BmwCarFrame implements CarFrame {@Overridepublic void getCarFrame() {System.out.println("宝马车架完工");}
}public class BenzCarFrame implements CarFrame {@Overridepublic void getCarFrame() {System.out.println("奔驰车架完工");}
}public interface Engine {void getEngine();
}public class BmwEngine implements Engine {@Overridepublic void getEngine() {System.out.println("宝马引擎完工");}
}public class BenzEngine implements Engine {@Overridepublic void getEngine() {System.out.println("奔驰引擎完工");}
}public interface Tire {void getTire();
}public class BmwTire implements Tire {@Overridepublic void getTire() {System.out.println("宝马轮胎完工");}
}public class BenzTire implements Tire {@Overridepublic void getTire() {System.out.println("奔驰轮胎完工");}
}public interface CarFactory {CarFrame createCarFrame();Engine createEngine();Tire createTire();
}public class BmwFactory implements CarFactory {@Overridepublic CarFrame createCarFrame() {return new BmwCarFrame();}@Overridepublic Engine createEngine() {return new BmwEngine();}@Overridepublic Tire createTire() {return new BmwTire();}
}public class BenzFactory implements CarFactory {@Overridepublic CarFrame createCarFrame() {return new BenzCarFrame();}@Overridepublic Engine createEngine() {return new BenzEngine();}@Overridepublic Tire createTire() {return new BenzTire();}
}public class Demo {public static void main(String[] args) {BmwFactory bmwFactory = new BmwFactory();CarFrame bmwFrame = bmwFactory.createCarFrame();bmwFrame.getCarFrame();Engine bmwEngine = bmwFactory.createEngine();bmwEngine.getEngine();Tire bmwTire = bmwFactory.createTire();bmwTire.getTire();System.out.println("宝马车生产完成");System.out.println("****************分割线*******************");BenzFactory benzFactory = new BenzFactory();CarFrame benzFrame = benzFactory.createCarFrame();benzFrame.getCarFrame();Engine benzEngine = benzFactory.createEngine();benzEngine.getEngine();Tire benzTire = benzFactory.createTire();benzTire.getTire();System.out.println("奔驰车生产完成");}
}