码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之工厂模式 练习

时间:2014-07-28 15:02:23      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   div   ar   new   type   设计   

设计模式中 最基本的工厂模式

感觉就是根据输入的类型决定选择何种类与进行何种操作。

跟面向过程中输入1则执行func1();输入2则执行func2()基本一致的想法

 

#include <iostream>

using namespace std;


enum eShoeType{ leather = 0,rubber};

class CShoe{
public:
	virtual void What() = 0;
};

class CLeatherShoe : public CShoe
{
public:
	void What() {cout << "I am leather shoe." << endl;}
};

class CRubberShoe : public CShoe
{
public:
	void What() {cout << "I am rubber shoe." << endl;}
};

class CShoeFactory
{
public:
	CShoe* GetShowInstance(eShoeType type)
	{
		cout << "工厂生产鞋子ing..." << endl;
		switch(type)
		{
		case leather:
			return new CLeatherShoe();
		case rubber:
			return new CRubberShoe();
		default:
			return NULL;
		}
	}
};

void TestWithCpp()
{
	CShoeFactory factory;
	CShoe* pShoe = NULL; 


	pShoe = factory.GetShowInstance(leather);
	if(NULL != pShoe)
	{
		pShoe->What();
		delete pShoe;
		pShoe = NULL;
	}
	

 	pShoe = factory.GetShowInstance(rubber);
	if(NULL != pShoe)
	{
		pShoe->What();
		delete pShoe;
		pShoe = NULL;
	}
}
////////////////////////////////////////////////////////
typedef struct SHOE{
	int type;
	void (*print_shoe)(struct SHOE*);
}Shoe;

void PrintLeatherShoe(Shoe* pShoe)
{
	if(NULL != pShoe)
		printf("I am leather shoe \n");
}

void PrintRubberShoe(Shoe* pShoe)
{
	if(NULL != pShoe)
		printf("I am rubber shoe \n");
}


Shoe* FactoryShoe(int type)
{
	Shoe* pShoe = NULL;

	pShoe = (Shoe*)malloc(sizeof(Shoe));
	if(NULL == pShoe)
		return NULL;
	
	memset(pShoe,0,sizeof(Shoe));

	if(leather == type)
	{
		pShoe->type = type;
		pShoe->print_shoe = PrintLeatherShoe;
	}else if( rubber == type)
	{
		pShoe->type = type;
		pShoe->print_shoe = PrintRubberShoe;
	}else
	{
		free(pShoe);
		pShoe = NULL;
		return NULL;
	}
	return pShoe;
}



void TestWithC()
{
	printf("\n\n 测试C版本工厂模式\n");


	Shoe* pShoe = FactoryShoe(leather);
	if(NULL != pShoe)
	{
		pShoe->print_shoe(pShoe);
		free(pShoe);
		pShoe = NULL;
	}

	pShoe = FactoryShoe(rubber);
	if(NULL != pShoe)
	{
		pShoe->print_shoe(pShoe);
		free(pShoe);
		pShoe = NULL;
	}

	pShoe = FactoryShoe(994);
	if(NULL != pShoe)
	{
		pShoe->print_shoe(pShoe);
		free(pShoe);
		pShoe = NULL;
	}


}


////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
	TestWithCpp();
	TestWithC();
	return 0;
}

 

设计模式之工厂模式 练习,布布扣,bubuko.com

设计模式之工厂模式 练习

标签:blog   os   io   div   ar   new   type   设计   

原文地址:http://www.cnblogs.com/itdef/p/3872722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!