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

c++简单工厂模式

2015-10-01 21:17 363 查看
// ConsoleApplication1.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include <iostream>

//#include "Factory.h"

using namespace std;

class Product

{

public:

virtual void display() = 0;

};

class ProductA:public Product

{

void display();

};

class ProductB:public Product

{

void display();

};

class Factory

{

public:

Product* CreatProduct(const char* strType)

{

if(strcmp(strType, "ProductA") == 0)

{

return new ProductA;

}

else if(strcmp(strType, "ProductB") == 0)

{

return new ProductB;

}

else

{

return 0;

}

}

};

void ProductA::display()

{

cout<<"this is ProductA"<<endl;

}

void ProductB::display()

{

cout<<"this is ProductB"<<endl;

}

int _tmain(int argc, _TCHAR* argv[])

{

Factory* pFactory = new Factory;

if(pFactory != NULL)

{

Product* pProductA = pFactory->CreatProduct("ProductA");

if(pProductA != NULL)

{

pProductA->display();

}

Product* pProductB = pFactory->CreatProduct("ProductB");

if(pProductB != NULL)

{

pProductA->display();

}

}

getchar();

return 0;

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