一、共享模式介绍
在软件系统采用纯粹对象方案的问题在于大量细粒度的对象会很快充斥在系统中,从而带来很高的运行时代价-主要指内存需求方面的代价。
享元模式尝试重用现有的同类对象,用唯一标识码(比如说id、hash等)判断,如果在内存中有,则返回这个唯一标识码所标识的对象,如果未找到匹配的对象,则创建新对象。
下面是UML类图
二、代码实现
#include<iostream>
#include<string>
#include <map>
using namespace std;
class personEX
{
protected:
string name;
int age;
public:
personEX(string strn, int a) :name(strn), age(a)
{
}
//显示信息
virtual void display()
{
cout << "普通人:" << name.c_str() << "\t" << age << "\t" << endl;
}
virtual ~personEX()
{
}
};
class Teacher :public personEX
{
protected:
string strid;
public:
Teacher(string name, int nage, string id) :personEX(name, nage)
{
strid = id;
}
void display() override
{
cout <<"老师:"<< name.c_str() << "\t" << age << "\t" << strid.c_str() << endl;
}
};
class Teacher_factory
{
private:
map<string, personEX*> m_map;
public:
Teacher_factory()
{
m_map.clear();
}
personEX *getobjbykey(string id)
{
auto it = m_map.find(id);
if (it == m_map.end())
{
//没有找到
cout << "没有找到" << id.c_str() << "的信息,将新建!\n";
char buf[24] = { 0 };
int age = 0;
cout << "请输入姓名:";
cin >> buf;
cout << "请输入年龄:";
cin >> age;
personEX *t = new Teacher(buf, age, id);
m_map.insert(std::pair<string, personEX *>(id, t));
return t;
}
else
{
return it->second;
}
}
~Teacher_factory()
{
while (!m_map.empty())
{
auto it = m_map.begin();
personEX *p = it->second;
m_map.erase(it);
delete p;
}
}
};
void main()
{
Teacher_factory *f = new Teacher_factory();
personEX *p1 = f->getobjbykey("ty001");
p1->display();
personEX *p2222 = f->getobjbykey("ty001");
p2222->display();
personEX *p3 = f->getobjbykey("ty002");
p3->display();
personEX *p4 = f->getobjbykey("ty002");
p4->display();
delete f;
system("pause");
}