抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口, 使得客户端在不指定产品的具体类型的情况下, 能够创建多个产品族的产品对象。
重要区别:
工厂模式:只能生产一个产品。(要么香蕉、 要么苹果)
抽象工厂:可以一下生产一个产品族(里面有很多产品组成)
模式中包含的角色及其职责:
抽象工厂(Creator)角色
抽象工厂模式的核心,包含对多个产品结构的声明,任何工厂类都必须实现这个接口。
具体工厂( Concrete Creator)角色
具体工厂类是抽象工厂的一个实现,负责实例化某个产品族中的产品对象。
抽象(Product)角色
抽象模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。
具体产品(Concrete Product)角色
抽象模式所创建的具体实例对象
应用实例:
产品变成了产品族,分为南方北方两个系列。而工厂则根据不同系列生产不同产品,单个系列中有多种产品,所有抽象工厂每种产品的生产方法都得有。
#include<iostream>
using namespace std;
// 水果的基类(抽象水果)
class AbFruit
{
public:
virtual void getFruit() = 0;
};
//抽象工厂类
class AbFactory
{
public:
virtual AbFruit* creatApple() = 0;
virtual AbFruit* creatBanana() = 0;
};
// 添加产品-------------------------------------
class SouthBanana: public AbFruit
{
public:
void getFruit(){
cout<<"SouthBanana"<<endl;
}
};
class SouthApple: public AbFruit
{
public:
void getFruit(){
cout<<"SouthApple"<<endl;
}
};
class NorthBanana: public AbFruit
{
public:
void getFruit(){
cout<<"NorthBanana"<<endl;
}
};
class NorthApple: public AbFruit
{
public:
void getFruit(){
cout<<"NorthApple"<<endl;
}
};
//-----------------------------------------------
// 专门建北方工厂
class NorthFactory:public AbFactory
{
public:
AbFruit * creatBanana()
{
return new NorthBanana;
}
AbFruit * creatApple()
{
return new NorthApple;
}
};
// 专门建南方工厂
class SouthFactory:public AbFactory
{
public:
AbFruit * creatBanana()
{
return new SouthBanana;
}
AbFruit * creatApple()
{
return new SouthApple;
}
};
int main()
{
AbFactory* ans = NULL;
AbFruit* myFruit = NULL;
ans = new SouthFactory; //工厂父类指针指向,南方工厂的对象
myFruit = ans->creatApple();//水果父类指针指向,南方工厂创建的苹果对象
myFruit->getFruit();//多态
delete myFruit;
myFruit = ans->creatBanana();
myFruit->getFruit();
delete myFruit;
delete ans;
ans = new NorthFactory;
myFruit = ans->creatBanana();
myFruit->getFruit();
delete myFruit;
myFruit = ans->creatApple();
myFruit->getFruit();
delete myFruit;
delete ans;
return 0;
}
三种工厂模式的区别:
- 简单工厂 : 用来生产同一等级结构中的任意产品。(对于增加新的产品,无能为力)
- 工厂方法 :用来生产同一等级结构中的固定产品。(支持增加任意产品)
- 抽象工厂 :用来生产不同产品族的全部产品。(对于增加新的产品,无能为力;支持增加产品族)