关闭

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

标签: 设计模式读书笔记Flyweight享元
233人阅读 评论(0) 收藏 举报
分类:

意图:

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

结构图:来自 《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");
}
附加:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:79341次
    • 积分:1289
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:0篇
    • 译文:0篇
    • 评论:38条
    文章分类
    最新评论