首页 > 代码库 > 享元模式

享元模式

1,我们做产品的时候,有很多产品是大同小异,所以我们细分化模块化是为了共用,而享元模式就是

2,代码很简单,看注视很清楚

// 享元模式.cpp : 定义控制台应用程序的入口点。
//



//公共的地方,仅仅需要一个对象在程序中,
//放在了map 中,由于map特性一个key 只能有一个value瞒住享元模式要求
//最大用处,内存优化,目的是降低程序内存使用
#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>


using namespace std;

class WebSite{
public:
	virtual void use() = 0;
};

class ConcreteWebSite :public WebSite{
public:
	string name;
public:
	ConcreteWebSite(string name) :name(name){}
	void use(){
		cout << name << "web site" << endl;
	}
};

class WebSiteFoctory{
private:
	map<string , WebSite*> wf;
public:
	WebSite *getWebSiteFoctory(string key){
		if (wf.find(key) == wf.end())
		{
			wf[key] = new ConcreteWebSite(key);
		}
		return wf[key];
	}

	int getWebSiteCount(){
		return wf.size();
	}
};







int _tmain(int argc, _TCHAR* argv[])
{

	WebSiteFoctory *factory = new WebSiteFoctory();
	WebSite *ws = factory->getWebSiteFoctory("good");
	ws->use();



	WebSite *ws1 = factory->getWebSiteFoctory("nice");
	ws1->use();

	WebSite *ws2 = factory->getWebSiteFoctory("very done");
	ws2->use();


	cout << "number of factory:"<<factory->getWebSiteCount() << endl;
	cin.get();
	return 0;
}



享元模式