意图:提供一个创建一系列或相关依赖对象的接口,而无需指定它的具体的类
代码:
#include <iostream>
using namespace std;
class Product1
{
public:
virtual int Behavior() = 0;
};
class Product1A:public Product1
{
public:
int Behavior()
{
cout << "Product1A finished\n";
return 1;
}
};
class Product1B:public Product1
{
public:
int Behavior()
{
cout << "Product1B finished\n";
return 1;
}
};
class Product2
{
public:
virtual int Behavior() = 0;
};
class Product2A:public Product2
{
public:
int Behavior()
{
cout << "Product2A finished\n";
return 1;
}
};
class Product2B:public Product2
{
public:
int Behavior()
{
cout << "Product2B finished\n";
return 1;
}
};
class AbstractFactory //使用了Factory Method工厂方法
{
public:
virtual Product1* CreateProduct1() = 0;
virtual Product2* CreateProduct2() = 0;
};
class FactoryA:public AbstractFactory //具体工厂使用了单例Singleton
{
private:
Product2A * p2A;
Product1A * p1A;
static FactoryA* mInstance;
FactoryA(): p2A(0), p1A(0) {}
public:
Product2* CreateProduct2()
{
if(p2A == 0)
p2A = new Product2A();
return p2A;
}
Product1* CreateProduct1()
{
if(p1A == 0)
p1A = new Product1A();
return p1A;
}
static FactoryA* GetInstance()
{
if(NULL == mInstance)
mInstance = new FactoryA();
return mInstance;
}
static void FreeInstance()
{
delete mInstance;
}
~FactoryA()
{
delete p2A;
delete p1A;
}
};
FactoryA* FactoryA::mInstance = NULL;
class FactoryB:public AbstractFactory
{
private:
Product2B * p2B;
Product1B * p1B;
static FactoryB* mInstance;
FactoryB(): p2B(0), p1B(0) {}
public:
Product2* CreateProduct2()
{
if(p2B == 0)
p2B = new Product2B();
return p2B;
}
Product1* CreateProduct1()
{
if(p1B == 0)
p1B = new Product1B();
return p1B;
}
static FactoryB* GetInstance()
{
if(NULL == mInstance)
mInstance = new FactoryB();
return mInstance;
}
static void FreeInstance()
{
delete mInstance;
}
~FactoryB()
{
delete p2B;
delete p1B;
}
};
FactoryB* FactoryB::mInstance = NULL;
int main()
{
AbstractFactory* factoryA = FactoryA::GetInstance();
Product1 *product1 = factoryA->CreateProduct1();
product1->Behavior();
FactoryA::FreeInstance();
AbstractFactory* factoryB = FactoryB::GetInstance();
Product2 *product2 = factoryB->CreateProduct2();
product2->Behavior();
FactoryB::FreeInstance();
return 1;
}
效果:
1 分离了具体的类
2 使得易于交换产品系列
3 有利于产品的一致性
4 难以支持新种类的产品
相关模式:
1 AbstractFactory类通常使用了Factory Method工厂方法
2 具体的工厂可以使之成为Singleton单件