设计模式读书笔记:flyweight(享元)

2015-07-10 17:17:24


意图:

运用共享技术有效地支持大量细粒度的对象。

结构图:来自 《23种设计模式 - 郗晓勇》

实现:https://github.com/panshiqu/patterns/tree/master/Flyweight

FlyweightFactory

#include "ConcreteFlyweight.h"
#include <map>

namespace NS_FLYWEIGHT {

class FlyweightFactory {
public:
	FlyweightFactory() {}
	virtual ~FlyweightFactory()
	{
		std::map<int, Flyweight *>::iterator itr = _flyweights.begin();
		for (; itr != _flyweights.end(); itr++)
			delete itr->second;

		_flyweights.clear();
	}
	Flyweight *getFlyweight(int key)
	{
		std::map<int, Flyweight *>::iterator itr = _flyweights.find(key);
		if (itr != _flyweights.end()) return itr->second;

		ConcreteFlyweight *flyweight = new ConcreteFlyweight();
		flyweight->setIntrinsicState(key);

		_flyweights.insert(std::make_pair(key, flyweight));
		return flyweight;
	}

private:
	std::map<int, Flyweight *> _flyweights;
};

} /* namespace NS_FLYWEIGHT */

Flyweight

#include <iostream>

namespace NS_FLYWEIGHT {

class Flyweight {
public:
	Flyweight() {}
	virtual ~Flyweight() {}
	virtual void operation(std::string extrinsicState) = 0;
};

} /* namespace NS_FLYWEIGHT */

ConcreteFlyweight

#include "Flyweight.h"

namespace NS_FLYWEIGHT {

class ConcreteFlyweight : public Flyweight
{
public:
	ConcreteFlyweight() : _intrinsicState(0) {}
	virtual ~ConcreteFlyweight() {}
	virtual void operation(std::string extrinsicState)
	{
		std::cout << extrinsicState << " ConcreteFlyweight - " << _intrinsicState << std::endl;
	}

	void setIntrinsicState(int intrinsicState)	{ _intrinsicState = intrinsicState; }

private:
	int _intrinsicState;
};

} /* namespace NS_FLYWEIGHT */

UnsharedConcreteFlyweight

#include "Flyweight.h"
#include <map>

namespace NS_FLYWEIGHT {

class UnsharedConcreteFlyweight : public Flyweight
{
public:
	UnsharedConcreteFlyweight() {}
	virtual ~UnsharedConcreteFlyweight() {}
	virtual void operation(std::string extrinsicState)
	{
		std::multimap<Flyweight *, std::string>::iterator itr = _flyweights.begin();
			for (; itr != _flyweights.end(); itr++)
			{
				std::string str = itr->second;
				if (str == "") str = extrinsicState;

				itr->first->operation(str);
			}
	}
	virtual void add(Flyweight *flyweight, std::string extrinsicState)
	{
		_flyweights.insert(make_pair(flyweight, extrinsicState));
	}
	virtual void remove(Flyweight *flyweight)
	{
		// do remove
	}

private:
	std::multimap<Flyweight *, std::string> _flyweights;
};

} /* namespace NS_FLYWEIGHT */

main

#include "Flyweight/FlyweightFactory.h"
#include "Flyweight/UnsharedConcreteFlyweight.h"
using namespace NS_FLYWEIGHT;
int main(void)
{
	FlyweightFactory ff;
	UnsharedConcreteFlyweight ucf;
	Flyweight *f1 = ff.getFlyweight(1);
	ucf.add(f1, "");
	Flyweight *f2 = ff.getFlyweight(1);
	ucf.add(f2, "black");
	ucf.operation("red");
}

附加: