意图:
运用共享技术有效地支持大量细粒度的对象。
结构图:来自 《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");
}附加:
本文介绍了一种通过使用享元模式来支持大量细粒度对象的有效方法,并提供了详细的C++实现案例,包括享元工厂和具体享元类的设计。
&spm=1001.2101.3001.5002&articleId=46832569&d=1&t=3&u=514c799f85cd4d128ab5762b47dbec80)
274

被折叠的 条评论
为什么被折叠?



