概述
抽象工厂模式与工厂方法模式最大的区别在于,工厂方法模式针对的是一个产品等级结构,而抽象工厂模式则需要面对多个产品等级结构,一个工厂等级结构可以负责多个不同产品等级结构中的产品对象的创建。
优点
抽象工厂模式隔离了具体类的生成,使得客户并不需要知道什么被创建。由于这种隔离,更换一个具体工厂就变得相对容易。增加新的具体工厂和产品族很方便,无须修改已有系统,符合“开闭原则”。
缺点
在添加新的产品对象时,难以扩展抽象工厂来生产新种类的产品,这是因为在抽象工厂角色中规定了所有可能被创建的产品集合,要支持新种类的产品就意味着要对该接口进行扩展,而这将涉及到对抽象工厂角色及其所有子类的修改,显然会带来较大的不便。增加新的工厂和产品族容易,增加新的产品等级结构麻烦。
类图
代码块
#include <iostream>
using namespace std;
class ProductA {
public:
virtual void show() = 0;
};
class ProductB {
public:
virtual void show() = 0;
};
class ProductA_1 : public ProductA {
public:
void show() {
cout << "i am product A_1 " << endl;
}
};
class ProductB_1 : public ProductB {
public:
void show() {
cout << " i am product b_1 " << endl;
}
};
class ProductA_2 : public ProductA {
public:
void show() {
cout << "i am product A_2 " << endl;
}
};
class ProductB_2 : public ProductB {
public:
void show() {
cout << " i am product b_2 " << endl;
}
};
class Factory {
public:
virtual ProductA *createProductA() = 0;
virtual ProductB *createProductB() = 0;
};
class FactoryA : public Factory {
public:
virtual ProductA *createProductA() {
return new ProductA_1();
}
virtual ProductB *createProductB() {
return new ProductB_1();
}
};
class FactoryB : public Factory {
public:
virtual ProductA *createProductA() {
return new ProductA_2();
}
virtual ProductB *createProductB() {
return new ProductB_2();
}
};
int main()
{
Factory *fc = new FactoryA();
ProductA *afc_pro = fc->createProductA();
afc_pro->show();
Factory *fc2 = new FactoryB();
ProductA *bfc_pro = fc2->createProductA();
bfc_pro->show();
return 0;
}