您的位置:首页 > 编程语言 > C语言/C++

C++实现简单工厂模式

2012-11-01 08:43 405 查看
/*
简单工厂模式:跟工厂模式很类似,不过在函数里面加上了逻辑判断
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:
Product *CreateProduct(const char *type)
{
if(strcmp(type, "product1") == 0)
{
return new Product1;
}
else if(strcmp(type, "product2") == 0)
{
return new Product2;
}
else
{
return NULL;
}
}
};

int main()
{
Factory *fac = new Factory();

Product *product1 = fac->CreateProduct("product1");
Product *product2 = fac->CreateProduct("product2");

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

system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: