FlyWeight.h
#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include <string>
using namespace std;
class CFlyWeight
{
public:
CFlyWeight(string _instanceState);
virtual~CFlyWeight();
virtual void Operation(const string & sInstance);
string GetInstanceString();
protected:
private:
string _instanceState;
};
class CConcerteFlyWeight:public CFlyWeight
{
public:
CConcerteFlyWeight(string _instanceState);
~CConcerteFlyWeight();
void Operation(const string & sInstance);
protected:
private:
};
#endif
FlyWeightFactory.h
#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_
#include "FlyWeight.h"
#include <vector>
using namespace std;
class CFlyWeightFactory
{
public:
CFlyWeightFactory();
~CFlyWeightFactory();
CFlyWeight * GetFlyWeight(const string & key);
protected:
private:
vector<CFlyWeight*> _fly;
};
#endif
FlyWeight.cpp
#include <iostream>
#include "FlyWeight.h"
using namespace std;
CFlyWeight::CFlyWeight(std::string _instanceState)
{
this->_instanceState=_instanceState;
}
CFlyWeight::~CFlyWeight()
{
}
void CFlyWeight::Operation(const std::string &sInstance)
{
}
string CFlyWeight::GetInstanceString()
{
return _instanceState;
}
CConcerteFlyWeight::CConcerteFlyWeight(std::string _instanceState):CFlyWeight(_instanceState)
{
cout<<_instanceState<<endl;
}
CConcerteFlyWeight::~CConcerteFlyWeight()
{
}
void CConcerteFlyWeight::Operation(const std::string &sInstance)
{
cout<<"CConcerteFlyWeight: "<<this->GetInstanceString()<<endl;
cout<<"[ "<<sInstance<<"]"<<endl;
}
FlyWeightFactory.cpp
#include <iostream>
#include "FlyWeightFactory.h"
using namespace std;
CFlyWeightFactory::CFlyWeightFactory()
{
}
CFlyWeightFactory::~CFlyWeightFactory()
{
}
CFlyWeight *CFlyWeightFactory::GetFlyWeight(const std::string &key)
{
vector<CFlyWeight *>::iterator it=_fly.begin();
for(; it < _fly.end(); ++it)
{
if((*it)->GetInstanceString() == key)
{
cout<<"find the Object: "<<key<<endl;
return (*it);
}
}
cout<<"Not find the Object"<<endl;
CFlyWeight * newKey=new CConcerteFlyWeight(key);
_fly.push_back(newKey);
return newKey;
}
main.cpp
#include <iostream>
#include "FlyWeight.h"
#include "FlyWeightFactory.h"
using namespace std;
int main() //Client
{
CFlyWeightFactory * fc=new CFlyWeightFactory();
CFlyWeight * fw1=fc->GetFlyWeight("Hello");
CFlyWeight * fw2=fc->GetFlyWeight("World");
CFlyWeight * fw3=fc->GetFlyWeight("Hello");
if(fc)
{
delete fc;
fc=0;
}
return 0;
}
在面向对象系统的设计何实现中,创建对象是最为常见的操作。这里面就有一个问题:如果一个应用程序使用了太多的对象,就会造成很大的存储开销。特别是对于大量轻量级(细粒度)的对象,比如在文档编辑器的设计过程中,我们如果为没有字母创建一个对象的话,系统可能会因为大量的对象而造成存储开销的浪费。例如一个字母“a”在文档中出现了100000次,而实际上我们可以让这一万个字母“a”共享一个对象,当然因为在不同的位置可能字母“a”有不同的显示效果(例如字体和大小等设置不同),在这种情况我们可以为将对象的状态分为“外部状态”和“内部状态”,将可以被共享(不会变化)的状态作为内部状态存储在对象中,而外部对象(例如上面提到的字体、大小等)我们可以在适当的时候将外部对象最为参数传递给对象(例如在显示的时候,将字体、大小等信息传递给对象)。
Flyweight模式中有一个类似Factory模式的对象构造工厂FlyweightFactory,当客户程序员(Client)需要一个对象时候就会向FlyweightFactory发出请求对象的消息GetFlyweight()消息,FlyweightFactory拥有一个管理、存储对象的“仓库”(或者叫对象池,vector实现),GetFlyweight()消息会遍历对象池中的对象,如果已经存在则直接返回给Client,否则创建一个新的对象返回给Client