享元--程序中会使用到大量的对象,这些对象耗费大量的内存,这些对象有相同的
地方(内部的状态)可以共享,可以用一个简单工厂类去返回已经存在的对象,不存
在的则创建,这些对象用一个容器存放。使用对象时可以再传入外部的状态。
// flyweight.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Flyweight
{
public:
//map会使用空构造
Flyweight()
{
}
Flyweight(string intrinsicState)
{
this->intrinsicState = intrinsicState;
}
virtual void operation(string extrinsicState)
{
cout << "Flyweight::operation()" << endl;
}
string intrinsicState;
};
class ConcreteFlyweight:public Flyweight
{
public:
ConcreteFlyweight(string intrinsicState):Flyweight(intrinsicState)
{
}
void operation(string extrinsicState)
{
cout << "intrinsicState: " << this->intrinsicState << endl;
cout << "extrinsicState: " << extrinsicState << endl;
}
};
class FlyweightFactory
{
public:
//静态成员函数要使用静态成员
static FlyweightFactory *getInstance()
{
if(f == NULL)
{
f = new FlyweightFactory();
}
return f;
}
Flyweight * getFlyweight(string intrinsicState)
{
if(1 != m.count(intrinsicState))
{
//要使用多态,这里要放指针,放对象不行
m[intrinsicState] = new ConcreteFlyweight(intrinsicState);
}
return m[intrinsicState];
}
~FlyweightFactory()
{
cout << "~FlyweightFactory" << endl;
//new的内存要释放
if(!m.empty())
{
map<string,Flyweight *>::iterator it = m.begin();
while(it != m.end())
{
cout << it->first << endl;
delete it->second;
it++;
}
}
/* 这个代码要注释掉,因为main中的fc与这里的f指的是相同的内存,
在delete时,先调用析构函数,会释放一遍内存,完了delete还要再释放一遍
if(NULL != f)
{
delete f;
f = NULL;
}
*/
}
protected:
FlyweightFactory()
{
f = NULL;
m.clear();
}
static FlyweightFactory *f;
map<string,Flyweight*> m;
};
//静态成员初始化
FlyweightFactory * FlyweightFactory::f = NULL;
int main()
{
FlyweightFactory *fc = FlyweightFactory::getInstance();
Flyweight *f1 = fc->getFlyweight("f1");
Flyweight *f2 = fc->getFlyweight("f2");
Flyweight *f3 = fc->getFlyweight("f1");
f1->operation("o1");
f2->operation("o2");
f3->operation("o3");
delete fc;
return 0;
}