//享元模式(英语:Flyweight Pattern)是一种软件设计模式。它使用共享物件,用来尽可能
//减少内存使用量以及分享资讯给尽可能多的相似物件;它适合用于只是因重复而导致使用无法
//令人接受的大量内存的大量物件。通常物件中的部分状态是可以分享。常见做法是把它们放在
//外部数据结构,当需要使用时再将它们传递给享元。
#include <iostream>
#include <string>
#include "map"
using namespace std;
class animal
{
public:
animal(string name, int id)
{
this->m_name = name;
this->id = id;
}
virtual void printT() = 0;
virtual ~animal(){};
protected:
string m_name;
int id;
};
class dog : public animal
{
public:
dog(string _name, int _id) : animal(_name, _id)
{
}
void printT()
{
cout << "name:" << m_name << " id:" << id << endl;
}
virtual ~dog()
{
cout << "name:" << m_name << " id:" << id << "xi gou" << endl;
}
};
class FlyWeightdogFactory
{
public:
FlyWeightdogFactory()
{
mymap.clear();
}
animal* creat_animal(int id)
{
auto ptr = mymap.find(id);
if (ptr == mymap.end())
{
string name_t;
cout << "not exit yet, input name!\n";
cin >> name_t;
animal* res = new dog(name_t, id); //
mymap[id] = res;
return res;
}
else
{
return ptr->second;
}
}
~FlyWeightdogFactory()
{
while (!mymap.empty())
{
map<int, animal*>::iterator it = mymap.begin();
delete it->second;
mymap.erase(it); //把第一个结点 从容器中删除
}
}
public:
map<int, animal*> mymap;
};
void main()
{
FlyWeightdogFactory* fac = new FlyWeightdogFactory();
animal* pet1 = fac->creat_animal(260985);
pet1->printT();
animal* pet2 = fac->creat_animal(260985);
pet1->printT();
delete fac;
//system("pause");
return;
}