享元模式(Flyweight)运用共享技术有效地支持大量细粒度的对象。
//Flyweight.h
#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include <iostream>
#include <string>
using namespace std;
class FlyWeight
{
public:
virtual void Operation(const string& extrinsicState){}
string GetIntrinsicState()
{
return _inSt;
}
protected:
FlyWeight(string insrinsicState)
{
_inSt = insrinsicState;
}
private:
string _inSt;
};
class ConcreteFlyweight:public FlyWeight
{
public:
ConcreteFlyweight(string insrinsicState):FlyWeight(insrinsicState)
{
cout<<"ConcreteFlyweight Build..."<<insrinsicState<<endl;
}
void Operation(const string& extrinsicState)
{
cout<<"ConcreteFlyweight insrinsicState ["<<GetIntrinsicState()<<"] extrinsicState ["
<<extrinsicState<<"]"<<endl;
}
};
#endif
/*
Flyweight.h
一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理的共享
Flyweight,当用户请求一个Flyweight时,Flyweight对象提供一个已创建的
实例或者创建一个。
*/
#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_
#include "Flyweight.h"
#include <vector>
#include <string>
using namespace std;
class FlyWeightFactory
{
public:
FlyWeight* GetFlyweight(const string& key)
{
vector<FlyWeight*>::iterator it = _fly.begin();
for (;it!=_fly.end();it++)
{
if ((*it)->GetIntrinsicState()==key)
{
cout<<"already created by users..."<<endl;
return *it;
}
}
FlyWeight* fn = new ConcreteFlyweight(key);
_fly.push_back(fn);
return fn;
}
private:
vector<FlyWeight*> _fly;
};
#endif
//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;
}