抽象工厂模式
在工厂模式中提到,为了解决简单工厂模式的不足(不满足开闭原则),工厂模式将工厂类抽象为一个公共类,只定义了基本的接口,而将对象的创建工作推迟到其子类中,这样当我们新增一个产品类的时候,只需要创建一个该产品类对应的工厂,并且继承公共的工厂类即可。
抽象工厂模式,就好比是多个工厂方法模式的叠加。抽象工厂创建的是一系列相关的对象,其中创建的实现其实就是采用的工厂方法模式。在工厂Factory中的每一个方法,就好比是一条生产线,而生产线实际需要生产什么样的产品,这是由工厂类的子类去决定的,这样便延迟了具体子类的实例化;同时集中化了生产线的管理,节省了资源的浪费。
例子(已测试)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <iostream>
using namespace std;
class Tree { public: virtual void print(){}; };
class TreeA : public Tree { public: void print() { cout << "This is Tree A" << endl; } };
class TreeB : public Tree { public: void print() { cout << "This is Tree B" << endl; } };
class Cat { public: virtual void print(){}; };
class CatA : public Cat { public: void print() { cout << "This is Cat A" << endl; } };
class CatB : public Cat { public: void print() { cout << "This is Cat B" << endl; } };
class Factory { public: virtual Tree *createTree() = 0; virtual Cat *createCat() = 0; };
class Factory1 : public Factory { public: Tree *createTree() { return new TreeA(); } Cat *createCat() { return new CatA(); } }; class Factory2 : public Factory { public: Tree *createTree() { return new TreeB(); } Cat *createCat() { return new CatB(); } };
int main() { Factory *factory1 = new Factory1(); Tree *tree1 = factory1->createTree(); Cat *cat1 = factory1->createCat();
tree1->print(); cat1->print();
Factory *factory2 = new Factory2(); Tree *tree2 = factory2->createTree(); Cat *cat2 = factory2->createCat();
tree2->print(); cat2->print();
if (factory1 != NULL) { delete factory1; factory1 = NULL; } if (tree1 != NULL) { delete tree1; tree1 = NULL; } if (cat1 != NULL) { delete cat1; cat1 = NULL; }
if (factory2 != NULL) { delete factory2; factory2 = NULL; } if (tree2 != NULL) { delete tree2; tree2 = NULL; } if (cat2 != NULL) { delete cat2; cat2 = NULL; } return 0; }
|
输出:
This is Tree A
This is Cat A
This is Tree B
This is Cat B
总结
- 工厂方法模式适用于产品种类结构单一的场合,为一类产品提供创建的接口;而抽象工厂方法适用于产品种类结构多的场合,主要用于创建一组(有多个种类)相关的产品,为它们提供创建的接口;就是当具有多个抽象角色时,抽象工厂便可以派上用场。
- 简单工厂模式->工厂模式->抽象工厂模式 本质上是同一种设计模式,具备层层递进的关系,有利于加深我们对于设计模式的理解和演进