工厂模式--c++实现
2015-12-18 17:37
113 查看
1、基类与子类 (state_init、state_routing、state_exexute:将要通过工厂生产的子类)
class state
{
public:
virtual void process() = 0;
};
class state_init : virtual public state
{
public:
virtual void process(){
cout << "state_init. process" << endl;
}
};
class state_routing : virtual public state
{
public:
virtual void process(){
cout << "state_routing. process" << endl;
}
};
class state_execute : virtual public state
{
public:
virtual void process(){
cout << "state_execute. process" << endl;
}
};
2、工厂类
class statefactory
{
public:
static state* generate_state(const string& operate){
if (operate == "init"){
return new state_init();
}else if (operate == "routing"){
return new state_routing();
}else if (operate == "execute"){
return new state_execute();
}else{
return NULL;
}
}
};
3、应用
int main()
{
state* pinit = statefactory::generate_state("init");
state* proute = statefactory::generate_state("routing");
state* pexecute = statefactory::generate_state("execute");
if (pinit){
pinit->process();
delete pinit;
pinit = NULL;
}else{
cout << "pinit is null" << endl;
}
if (proute){
proute->process();
delete proute;
proute = NULL;
}else{
cout << "proute is null" << endl;
}
if (pexecute){
pexecute->process();
delete pexecute;
pexecute = NULL;
}else{
cout << "pexecute is null" << endl;
}
return 0;
}
class state
{
public:
virtual void process() = 0;
};
class state_init : virtual public state
{
public:
virtual void process(){
cout << "state_init. process" << endl;
}
};
class state_routing : virtual public state
{
public:
virtual void process(){
cout << "state_routing. process" << endl;
}
};
class state_execute : virtual public state
{
public:
virtual void process(){
cout << "state_execute. process" << endl;
}
};
2、工厂类
class statefactory
{
public:
static state* generate_state(const string& operate){
if (operate == "init"){
return new state_init();
}else if (operate == "routing"){
return new state_routing();
}else if (operate == "execute"){
return new state_execute();
}else{
return NULL;
}
}
};
3、应用
int main()
{
state* pinit = statefactory::generate_state("init");
state* proute = statefactory::generate_state("routing");
state* pexecute = statefactory::generate_state("execute");
if (pinit){
pinit->process();
delete pinit;
pinit = NULL;
}else{
cout << "pinit is null" << endl;
}
if (proute){
proute->process();
delete proute;
proute = NULL;
}else{
cout << "proute is null" << endl;
}
if (pexecute){
pexecute->process();
delete pexecute;
pexecute = NULL;
}else{
cout << "pexecute is null" << endl;
}
return 0;
}
相关文章推荐
- C++STL之map
- 修改在VS2010环境下建立的C++项目名称
- C语言实现字符串替换函数
- C++ map用法——关联式容器
- C++中的explicit关键字
- C++11: bitset
- C++&杂谈
- More Effective C++ 第五部分 技术
- 常见的面试C++问题
- windows下用C语言实现ping
- C语言入门----位运算
- C++中各种new/delete总结
- VS2013 C++ error C1083: 无法打开源文件: “SDKDDKVer.h”, "stdio.h", "tchar.h"
- 不交作业
- 黑马程序员 - OC语言 - NSArray 读写文件
- 黑马程序员 - OC语言 - 重写构造方法
- boost 1.56.0 编译及使用
- C++中的容器类详解
- C语言之预处理
- liunx c语言制作 微型web服务器 300行代码