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;
}
//
#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;
}
相关文章推荐
- C++容器(二):关联容器简介
- C++容器(二):关联容器简介
- leetcode 242 :Valid Anagram
- 位操作基础篇之位操作全面总结
- #LeetCode# #C++# Symmetric Tree
- EffectiveC++
- 从C++strStr到字符串匹配算法
- c和c++易错点拾露
- C语言之进制、位运算符、数组
- 读取数量不定的输入数据
- c++primer读书笔记零(开读篇)
- C语言及程序设计.第二十三课.项目6.前导0的数字
- c++ 读写Excel及数据导入SQLServer
- C语言及程序设计.第二十三课.项目5.我的加班费
- 单链表顺序存储相关操作的c语言实现
- C++ 多重继承和虚继承的内存布局
- C++ | 数组与指针
- 2013级别C++文章9周(春天的)工程——运算符重载(两)
- 08.C语言数组
- 07.C语言内存分析