设计模式之享元模式

【定义】享元模式(Flyweight),运用共享技术有效的支持大量细粒度的对象。

【场景】依旧以手机为例,手机有很多属性,品牌,手机号码,手机颜色等,现在假设手机有品牌和手机号码两种属性。手机品牌有Iphone,Sumsung,Nokia三种,但是手机号码却有千千万万,这千千万万的手机号码便是大量的细粒度的对象。为了减少对内存空间的需求,可以将号码提取出来单独存储,这样便只需要创建3个对象就可以表示千千万万的手机了。

【UML】


【代码】

#include <iostream>
#include <String>
#include <map>

using namespace std;

class Phone
{
public:
	virtual void display() = 0;
};

class Iphone : public Phone
{
public:
	void display()
	{
		cout<<"Iphone:";
	}
};

class Nokia : public Phone
{
public:
	void display()
	{
		cout<<"Nokia:";
	}
};


typedef enum _PhoneType{TYPEIPHONE, TYPENOKIA} PhoneType;	//品牌类型
typedef map<string, PhoneType> PhoneMap;					//存储号码数据类型

class PhoneFactory
{
private:
	PhoneMap phones;	//将号码提取出来单独存储
	Phone* iphone;
	Phone* nokia;
public:
	PhoneFactory():iphone(NULL),nokia(NULL){}
	Phone* get_phone(string number, PhoneType type)
	{
		if(TYPEIPHONE == type)
		{
			if(NULL == iphone)
			{
				iphone = new Iphone;
			}
			phones.insert(make_pair(number, type));
			return iphone;
		}

		if(TYPENOKIA == type)
		{
			if(NULL == nokia)
			{
				nokia = new Nokia;
			}
			phones.insert(make_pair(number, type));
			return nokia;
		}
	}
	~PhoneFactory()
	{
		delete iphone;
		delete nokia;
	}
};

int main()
{
	PhoneFactory* factory = new PhoneFactory;

	Phone* iphone1 = factory->get_phone("10086", TYPEIPHONE);
	iphone1->display();
	cout<<"\tnumber:10086"<<endl;

	Phone* iphone2 = factory->get_phone("10087", TYPEIPHONE);
	iphone2->display();
	cout<<"\tnumber:10087"<<endl;

	Phone* iphone3 = factory->get_phone("10088", TYPEIPHONE);
	iphone3->display();
	cout<<"\tnumber:10088"<<endl;

	Phone* nokia = factory->get_phone("10010", TYPENOKIA);
	nokia->display();
	cout<<"\tnumber:10010"<<endl;

	delete factory;

	return 0;
}


【运行结果】



posted @ 2012-08-26 23:49  $逝水无痕$  阅读(112)  评论(0编辑  收藏  举报