设计模式——享元模式_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);
};

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

你可能感兴趣的:(设计模式——享元模式_Flyweight Pattern)