用代码和UML图化解设计模式之《工厂模式》

所谓工厂模式,其实就是用来产生实例的地方。生产某一类型的产品。因此也是利用了类管理和类多态的一个特性吧。

 

下面直接上图

 

在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;
}


 

这个模式,我还要很多思考。其实用很多值得思考的地方。有新的结果,我在写出来。敬请期待

更多文章,欢迎访问:

http://blog.csdn.net/wallwind

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值