C++实现设计模式——工厂模式
- 为什么用工厂模式
https://blog.youkuaiyun.com/yxh_1_/article/details/116010061?spm=1001.2014.3001.5501
- 简单工厂模式
简单工厂模式举个直白的例子就是,好比一个手机制造工厂,里面有几条手机制造生产线,我们只要给了对应的材料,就能制造出对应的手机。
简单的用代码实现如下:
#include <iostream>
using namespace std;
enum phoneType {
miType = 0,
huaweiType,
oppoType
};
class phone {
public:
virtual void show()=0;
};
class mi:public phone{
public:
void show() {
cout<<"mi phone create"<<endl;
}
};
class huawei: public phone {
public:
void show() {
cout<<"huawei phone create"<<endl;
}
};
class oppo: public phone {
public:
void show() {
cout<<"oppo phone create"<<endl;
}
};
#if 1
class Factory {
public:
phone* createPhone(enum phoneType type) {
if(type == miType) {
return new mi();
} else if (type == huaweiType) {
return new huawei();
} else if (type == oppoType){
return new oppo();
} else {
return NULL;
}
}
};
#endif
int main() {
Factory *f = new Factory();
f->createPhone(miType)->show();
f->createPhone(huaweiType)->show();
f->createPhon