设计模式中的享元模式,避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).
使用面向对象的技术时,虽然在开发过程中能过简化设计,可是在一切是对象的思想下,在一些小粒度,大数量的应用中,可能会导致对象数极具增大,导致消耗太多的内存。比如文本编辑器,如果一个字符就是一个对象,那么可想而知对象数是对少。
FlyWeight模式就是用来解决这种问题的,同一个对象多次出现。实现是通过一个pool(对象池)来实现的,已有的对象直接使用,没有的创建使用,放进pool中。一般会实现会使用到Factory模式。
还有一种说法其实就是Factory+Singleton 。
下面是类图
代码实现:
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
#include <string>
#include <iostream>
class FlyWeight
{
public:
FlyWeight(std::string _info);
virtual ~FlyWeight(){}
std::string getInfo() const {return info;}
virtual void operator1() = 0;
private:
std::string info;
};
#endif // FLYWEIGHT_H
#include "flyweight.h"
FlyWeight::FlyWeight(std::string _info):info(_info)
{
}
#ifndef CONCRETEFLYWEIGHT_H
#define CONCRETEFLYWEIGHT_H
#include "flyweight.h"
class ConcreteFlyWeight : public FlyWeight
{
public:
ConcreteFlyWeight(std::string _info);
~ConcreteFlyWeight(){}
void operator1(){}
};
#endif // CONCRETEFLYWEIGHT_H
#include "concreteflyweight.h"
ConcreteFlyWeight::ConcreteFlyWeight(std::string _info):FlyWeight(_info)
{
}
#ifndef FLYWEIGHTFACTORY_H
#define FLYWEIGHTFACTORY_H
#include "concreteflyweight.h"
#include <vector>
#include <string>
#include <iterator>
class FlyWeightFactory
{
public:
FlyWeightFactory();
~FlyWeightFactory();
int getPoolSize() const {return pool.size();}
FlyWeight* getFlyWeight(const std::string key);
private:
std::vector<FlyWeight*> pool;
};
#endif // FLYWEIGHTFACTORY_H
#include "flyweightfactory.h"
FlyWeightFactory::FlyWeightFactory()
{
}
FlyWeightFactory::~FlyWeightFactory()
{
std::vector<FlyWeight*>::iterator ite;
for (ite = pool.begin();ite != pool.end();++ite) {
delete (*ite);
}
pool.clear();
}
FlyWeight* FlyWeightFactory::getFlyWeight(const std::string key)
{
std::vector<FlyWeight*>::iterator ite;
for (ite = pool.begin();ite != pool.end();++ite) {
if ((*ite)->getInfo() == key) {
return (*ite);
}
}
FlyWeight * fly = new ConcreteFlyWeight(key);
pool.push_back(fly);
return fly;
}
#include <iostream>
using namespace std;
#include "flyweightfactory.h"
int main()
{
FlyWeightFactory *p = new FlyWeightFactory;
p->getFlyWeight("zhou");
p->getFlyWeight("zhou");
p->getFlyWeight("xiang");
p->getFlyWeight("chenchen");
p->getFlyWeight("chenchen");
p->getFlyWeight("ZhouXiangLoveChenChen");
p->getFlyWeight("ChenChenLoveZhouXiang");
cout << p->getPoolSize()<<'\n';
delete p;
return 0;
}
在pool中的只有5个对象