现在的位置: 首页 > 综合 > 正文

C++实现工厂模式

2013年02月09日 ⁄ 综合 ⁄ 共 741字 ⁄ 字号 评论关闭
/*
	工厂模式:定义一个创建对象的接口,让子类决定具体实现哪个类,让类的实例化延迟到子类中。
	Created by Phoenix_FuliMa
*/

#include <iostream>
using namespace std;

class Product
{
public:
	virtual void display() = 0;
};

class Product1:public Product
{
public:
	void display()
	{
		cout<<"I am product1..."<<endl;
	}
};

class Product2:public Product
{
public:
	void display()
	{
		cout<<"I am product2..."<<endl;
	}
};

class Factory
{
public:
	virtual Product *CreateProduct() = 0;
};

class Factory1:public Factory
{
public:
	Product *CreateProduct()
	{
		return new Product1();
	}
};

class Factory2:public Factory
{
public:
	Product *CreateProduct()
	{
		return new Product2();
	}
};


int main()
{
	Factory1 *fac1 = new Factory1();
	Factory2 *fac2 = new Factory2();

	Product *product1 = fac1->CreateProduct();
	Product *product2 = fac2->CreateProduct();

	product1->display();
	product2->display();

	system("pause");
	return 0;

}

抱歉!评论已关闭.