C++实现抽象工厂模式

/*
	抽象工厂模式:创建一系列相关或相互依赖的对象的接口,而无需指定他们具体的类
	Created by Phoenix_FuliMa
*/
#include <iostream>
using namespace std;

class ProductA
{
public:
	virtual void display()
	{}
};
class ProductA_1:public ProductA
{
public:
	void display()
	{
		cout<<"productA_1 is unhappy"<<endl;
	}
};
class ProductA_2:public ProductA
{
public:
	void display()
	{
		cout<<"productA_2 is unhappy too"<<endl;
	}
};

class ProductB
{
public:
	virtual void display()
	{

	}
};
class ProductB_1:public ProductB
{
public:
	void display()
	{
		cout<<"productB_1 is unhappy.."<<endl;
	}
};
class ProductB_2:public ProductB
{
public:
	void display()
	{
		cout<<"productB_2 is unhappy"<<endl;
	}
};
class AbstactFactory
{
public:
	virtual ProductA* CreateProductA() = 0;
	virtual ProductB* CreateProductB() = 0;
};

class Factory1:public AbstactFactory
{
public:
	ProductA* CreateProductA()
	{
		return new ProductA_1();
	}
	ProductB* CreateProductB()
	{
		return new ProductB_1();
	}
};

class Factory2:public AbstactFactory
{
public:
	ProductA* CreateProductA()
	{
		return new ProductA_2();
	}
	ProductB* CreateProductB()
	{
		return new ProductB_2();
	}
};

int main()
{
	Factory1* factory1 = new Factory1();
	Factory2* factory2 = new Factory2();

	ProductA  *producta1 = factory1->CreateProductA();
	ProductA  *producta2 = factory2->CreateProductA();

	producta1->display();
	producta2->display();
	
	delete producta2;
	delete producta1;
	delete factory1;
	delete factory2;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值