设计模式——享元模式_Flyweight Pattern

享元模式:

Use sharing to support large numbers of fine-grained objects efficiently. (使用共享对象可有效地支持大量的细粒度的对象。)



UML类图:


C++代码实现:

#include <iostream>
#include <string>
#include <map>
using namespace std;

class Flyweight {
public:
	Flyweight(const string& str) { _flyweightObj = str; }
	virtual void Operator() { cout << "call Flyweight::Operator() ---> " << _flyweightObj << endl; }

private:
	string _flyweightObj;
};


class ConcreteFlyweight : public Flyweight {
public:
	ConcreteFlyweight(const string& obj) 
		: Flyweight(obj) {  }
};

class  FlyweightFactory {
public:
	Flyweight* CreateObject(const string& obj) {
		typedef map<string, Flyweight*>::iterator MapIter;
		MapIter iter = _ObjectPool.find(obj);
		if (iter!=_ObjectPool.end()) { // find existed obj
			cout << "existed object! (" << iter->first << ")" << endl;
			return iter->second;
		} else { // not found
			Flyweight* pFlyweight = new Flyweight(obj);
			_ObjectPool.insert(make_pair(obj, pFlyweight));
			return pFlyweight;
		}
	}

         ~FlyweightFactory() {
		if (!_ObjectPool.empty()) {
			typedef map<string, Flyweight*>::iterator MapIter;
			for (MapIter iter=_ObjectPool.begin(); iter!=_ObjectPool.end(); ++iter) {
				delete iter->second;
				cout << "delete object (" << iter->first << ")" << endl;
			}
		}
	}
private:
	map<string, Flyweight*> _ObjectPool;
};

#include "Flyweight.h"

int main() {
	FlyweightFactory *pFlyFactory = new FlyweightFactory();
	ConcreteFlyweight *pFly1 = (ConcreteFlyweight*)pFlyFactory->CreateObject(string("hello"));
	pFly1->Operator();
	ConcreteFlyweight *pFly2 = (ConcreteFlyweight*)pFlyFactory->CreateObject(string("world"));
	pFly2->Operator();
	ConcreteFlyweight *pFly3 = (ConcreteFlyweight*)pFlyFactory->CreateObject(string("hello"));
	pFly3->Operator();

	delete pFlyFactory;
	return (0);
};

享元模式大大减少应用程序创建的对象,需要注意的的一点是:分离出外部状态和内部状态(被共享,与环境无关不发生改变)。所以不应该出现一个操作改变了内部状态,同时修改了外部状态,这是绝对不允许的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值