设计模式-创建型模式之 Abstract Factory(抽象工厂)

本文探讨了工厂方法模式在创建一系列或相关依赖对象时的作用,通过实例展示了如何使用抽象工厂和具体工厂来分离类的具体实现,易于交换产品系列并保持产品一致性。同时,文章深入分析了工厂方法模式在实现过程中的优势与局限。
摘要由CSDN通过智能技术生成

意图:提供一个创建一系列或相关依赖对象的接口,而无需指定它的具体的类

代码:

#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单件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值