1.概念
《设计模式》一书中对于抽象工厂模式是这样定义的:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
2、示例
- // 产品 Plant接口
- public interface Plant { }//标志接口
- //具体产品PlantA,PlantB
- public class PlantA implements Plant {
- public PlantA () {
- System.out.println("create PlantA !");
- }
- public void doSomething() {
- System.out.println(" PlantA do something ...");
- }
- }
- public class PlantB implements Plant {
- public PlantB () {
- System.out.println("create PlantB !");
- }
- public void doSomething() {
- System.out.println(" PlantB do something ...");
- }
- }
- // 产品 Fruit接口
- public interface Fruit { }
- //具体产品FruitA,FruitB
- public class FruitA implements Fruit {
- public FruitA() {
- System.out.println("create FruitA !");
- }
- public void doSomething() {
- System.out.println(" FruitA do something ...");
- }
- }
- public class FruitB implements Fruit {
- public FruitB() {
- System.out.println("create FruitB !");
- }
- public void doSomething() {
- System.out.println(" FruitB do something ...");
- }
- }
- // 抽象工厂方法
- public interface AbstractFactory {
- public Plant createPlant();
- public Fruit createFruit();
- }
- //具体工厂方法
- public class FactoryA implements AbstractFactory {
- public Plant createPlant() {
- return new PlantA();
- }
- public Fruit createFruit() {
- return new FruitA();
- }
- }
- public class FactoryB implements AbstractFactory {
- public Plant createPlant() {
- return new PlantB();
- }
- public Fruit createFruit() {
- return new FruitB();
- }
- }
- //调用工厂方法
- public Client {
- public method1() {
- AbstractFactory instance = new FactoryA();
- instance.createPlant();
- }
- }
3、抽象工厂模式与工厂方法模式的区别
可以这么说,工厂方法模式是一种极端情况的抽象工厂模式,而抽象工厂模式可以看成是工厂方法模式的一种推广。
(1)、其实工厂方法模式是用来创建一个产品的等级结构的,而抽象工厂模式是用来创建多个产品的等级结构的。工厂方法创建一般只有一个方法,创建一种产品。抽象工厂一般有多个方法,创建一系列产品。
(2)、工厂方法模式只有一个抽象产品类,而抽象工厂模式有多个。工厂方法模式的具体工厂类只能创建一个具体产品类的实例,而抽象工厂模式可以创建多个。
简而言之->
工厂方法模式:一个抽象产品类,可以派生出多个具体产品类。
一个抽象工厂类,可以派生出多个具体工厂类。
每个具体工厂类只能创建一个具体产品类的实例。
抽象工厂模式:多个抽象产品类,每个抽象产品类可以派生出多个具体产品类。
一个抽象工厂类,可以派生出多个具体工厂类。
每个具体工厂类可以创建多个具体产品类的实例。
抽象工厂模式

2159

被折叠的 条评论
为什么被折叠?



