所谓工厂模式,其实就是用来产生实例的地方。生产某一类型的产品。因此也是利用了类管理和类多态的一个特性吧。
下面直接上图
在Factory 中产生human的实例,
然后通过实例来调用方法。
// Factory.cpp : 定义控制台应用程序的入口点。
/************************************************************************/
/* @filename Factory.cpp
@author wallwind
@createtime 2012/10/20 10:36
@function 工厂模式
@email wochenglin@qq.com
*/
/************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
enum HumanType
{
white = 0,black,yello,
};
class Human
{
public:
//Human(){}
virtual~Human(){}
virtual void run() = 0;
virtual void sleep()=0;
};
class WhiteMan:public Human
{
public:
WhiteMan(){}
~WhiteMan(){}
void run()
{
cout<<"WhiteMan:run()"<<endl;
}
void sleep()
{
cout<<"WhiteMan:sleep()"<<endl;
}
};
class BlackMan:public Human
{
public:
BlackMan(){}
~BlackMan(){}
void run()
{
cout<<"BlackMan:run()"<<endl;
}
void sleep()
{
cout<<"BlackMan:sleep()"<<endl;
}
};
class YellowMan:public Human
{
public:
YellowMan(){}
~YellowMan(){}
void run()
{
cout<<"YellowMan:run()"<<endl;
}
void sleep()
{
cout<<"YellowMan:sleep()"<<endl;
}
};
class HumanFactory
{
public:
HumanFactory(){}
~HumanFactory(){}
static Human* createHuman(HumanType htp)
{
Human* human;
switch (htp)
{
case white:
human = new WhiteMan();
break;
case black:
human = new BlackMan();
break;
case yello:
human = new YellowMan();
default:
human = NULL;
}
return human;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int type = rand()%2;
cout<<type<<endl;
Human * mhum;
mhum = HumanFactory::createHuman((HumanType)type);
if (mhum ==NULL)
{
cout<<"no human"<<endl;
exit(0);
}
mhum->run();
mhum->sleep();
return 0;
}
这个模式,我还要很多思考。其实用很多值得思考的地方。有新的结果,我在写出来。敬请期待
更多文章,欢迎访问: