标签:设计模式 design-pattern 享元模式 flyweight
在开发时,如果创建很多对象,就会造成很大的内存开销,特别是大量轻量级(细粒度)的对象,还会造成内存碎片。Flyweight模式就是运用共享技术,有效支持大量细粒度对象的设计模式。
其类结构图如下:
在FlyweightFactory中有一个管理、存储对象的对象池,当调用GetFlyweight时会首先遍历对象池,如果已存在,则返回,否则创建新对象添加到对象池中。有些对象可能不想被共享,那么就使用UnshareConcreteFlyweight。
实现:
//Flyweight.h
//Flywight.h
#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include<string>
using std::string;
class Flyweight
{
public:
virtual ~Flyweight();
virtual void Operation(const string& extrinsicState);
string GetIntrinsicState();
protected:
Flyweight(string intrinsicState);
private:
string _intrinsicState;
};
class ConcreteFlyweight :public Flyweight
{
public:
ConcreteFlyweight(string intrinsicState);
~ConcreteFlyweight();
void Operation(const string& extrinsicState);
};
#endif
//Flyweight.cpp
//Flyweight.cpp
#include"Flyweight.h"
#include<iostream>
using std::cout;
Flyweight::Flyweight(string intrinsicState)
{
_intrinsicState = intrinsicState;
}
Flyweight::~Flyweight()
{}
void Flyweight::Operation(const string& extrinsicState)
{}
string Flyweight::GetIntrinsicState()
{
return _intrinsicState;
}
ConcreteFlyweight::ConcreteFlyweight(string intrinsicState) :Flyweight(intrinsicState)
{
cout << "ConcreteFlyweight Build..." << std::endl;
}
ConcreteFlyweight::~ConcreteFlyweight()
{}
void ConcreteFlyweight::Operation(const string& extrinsicState)
{
cout << "ConcreteFlyweight:内蕴[" << this->GetIntrinsicState() << "]外蕴["
<< extrinsicState << "]" << std::endl;
}
//FlyweightFactory.h
//FlyweightFactory.h
#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_
#include"Flyweight.h"
#include<string>
#include<vector>
using std::string;
using std::vector;
class FlyweightFactory
{
public:
FlyweightFactory();
~FlyweightFactory();
Flyweight* GetFlyweight(const string& key);
private:
vector<Flyweight*> _fly;
};
#endif
//FlyweightFactory.cpp
//FlyweightFactory.cpp
#include"FlyweightFactory.h"
#include<iostream>
#include<string>
#include<cassert>
using std::string;
using std::cout;
FlyweightFactory::FlyweightFactory()
{}
FlyweightFactory::~FlyweightFactory()
{}
Flyweight* FlyweightFactory::GetFlyweight(const string& key)
{
vector<Flyweight*>::iterator it = _fly.begin();
for (; it != _fly.end(); it++)
{
if ((*it)->GetIntrinsicState() == key)
{
cout << "already create by users..." << std::endl;
return *it;
}
}
Flyweight* fn = new ConcreteFlyweight(key);
_fly.push_back(fn);
return fn;
}
//main.cpp
#include"Flyweight.h"
#include"FlyweightFactory.h"
int main()
{
FlyweightFactory* fc = new FlyweightFactory();
Flyweight* fw1 = fc->GetFlyweight("hello");
Flyweight* fw2 = fc->GetFlyweight("world");
Flyweight* fw3 = fc->GetFlyweight("hello");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:设计模式 design-pattern 享元模式 flyweight
原文地址:http://blog.csdn.net/kangroger/article/details/46882773