Flyweight.h
#pragma once
#include <string>
using namespace std;
class Flyweight
{
public:
~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);
protected:
private:
};
Flyweight.cpp
#include "Flyweight.h"
#include <iostream>
using namespace std;
Flyweight::~Flyweight()
{
}
void Flyweight::Operation(const string & extrinsicState)
{
}
string Flyweight::GetIntrinsicState()
{
return _intrinsicState;
}
Flyweight::Flyweight(string intrinsicState)
{
_intrinsicState = intrinsicState;
}
ConcreteFlyWeight::ConcreteFlyWeight(string intrinsicState):Flyweight(intrinsicState)
{
cout << "ConcreteFlyweight Build....."<<intrinsicState<<endl;
}
ConcreteFlyWeight::~ConcreteFlyWeight()
{
}
void ConcreteFlyWeight::Operation(const string & extrinsicState)
{
cout << "ConcreteFlyweight: 内 蕴["<<this->GetIntrinsicState()<<"] 外 蕴["<<extrinsicState<<"]"<<endl;
}
FlyWeightFactory.h
#pragma once
#include "Flyweight.h"
#include <string>
#include <vector>
using namespace std;
class FlyWeightFactory
{
public:
FlyWeightFactory();
~FlyWeightFactory();
Flyweight* GetFlyweight(const string& key);
private:
vector<Flyweight*> _fly;
};
FlyWeightFactory.cpp
#include "FlyWeightFactory.h"
#include <iostream>
using namespace std;
FlyWeightFactory::FlyWeightFactory()
{
}
FlyWeightFactory::~FlyWeightFactory()
{
}
Flyweight * FlyWeightFactory::GetFlyweight(const string & key)
{
auto iter = _fly.begin();
for (; iter != _fly.end(); iter++)
{
if ((*iter)->GetIntrinsicState() == key)
{
cout << "already created by users...."<<endl;
return *iter;
}
}
Flyweight* fn = new ConcreteFlyWeight(key);
_fly.push_back(fn);
return fn;
}
main.cpp
#include <iostream>
#include "FlyWeightFactory.h"
using namespace std;
int main(int argc, char* argv[])
{
/*Flyweight 模式
在实现过程中主要是要为共享对象提供一个存放的“仓库”(对象池),
这里是通过 C++ STL 中 Vector 容器*/
FlyWeightFactory* fc = new FlyWeightFactory();
Flyweight* fw1 = fc->GetFlyweight("hhhhh");
Flyweight* fw2 = fc->GetFlyweight("lllll");
Flyweight* fw3 = fc->GetFlyweight("hhhhh");
ConcreteFlyWeight* fw4 = new ConcreteFlyWeight("2");
fw4->Operation("1");
system("pause");
return 0;
}
ConcreteFlyweight Build.....hhhhh
ConcreteFlyweight Build.....lllll
already created by users....
ConcreteFlyweight Build.....2
ConcreteFlyweight: 内 蕴[2] 外 蕴[1]
请按任意键继续. . .
Flyweight 模式主要是要为共享对象提供一个存放的“仓库”(对象池),可以避免创建大量重复的对象,减少造成的存储开销