所謂工廠模式,其實就是用來產生實例的地方。生產某一類型的產品。因此也是利用了類管理和類多態的一個特性吧。
下面直接上圖
在Factory 中產生human的實例,
然後通過實例來調用方法。
- // Factory.cpp : 定義控制檯應用程序的入口點。
- /************************************************************************/
- /* @filename Factory.cpp
- @author wallwind
- @createtime 2012/10/20 10:36
- @function 工廠模式
- @email [email protected]
- */
- /************************************************************************/
- #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;