首页 > 代码库 > Flyweight模式
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;
}
Flyweight模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。