设计模式观后(c++还原之二十五 享元模式)

string int2string(int n) {
	char buffer[10] = {0};
	_itoa_s(n, buffer, 10, 10);
	return string(buffer);
}
//享元模式
//作者例子:报考系统的对象
//每个用户的访问就构造一个对象会导致内存不够,作者设立关键字:多个用户使用一块内存
//报考信息
class SignInfo {
private:
	string m_strID;//报名的ID
	string m_strLocation;//考试地点
	string m_strSubject;//考试科目
	
public:
	string GetID() {return m_strID;}
	void SetID(string id) {m_strID = id;}

	string GetLocation() {return m_strLocation;}
	void SetLocation(string location) {m_strLocation = location;}

	string GetSubject() {return m_strSubject;}
	void SetSubject(string subject) {m_strSubject = subject;}
};
//带对象池的报考信息
class SignInfoPool : public SignInfo {
	//定义对象池的key
private:
	string m_strKey;
public:
	SignInfoPool(string key) {
		m_strKey = key;
	}
	string GetKey() {
		return m_strKey;
	}
	void SetKey(string key) {
		m_strKey = key;
	}
};
//对象池的工厂类
class SignInfoFactory {
private:
	//池容器
	static map s_pool;
public:
	static SignInfo* SignInfo() {
		return new class SignInfo;
	}
	//从线程池获取对象
	static class SignInfo* GetSignInfo(string key) {
		class SignInfo* result = NULL;
		//池中没有对象,则建立,并放入。有就返回
		if (s_pool.find(key) != s_pool.end()) {
			cout << "直接从池中取出" < SignInfoFactory::s_pool;

class Client {
public:
	static void main() {
		//初始化对象池
		for (int i = 0; i < 4; i++)
		{
			string subject = "科目" + int2string(i);
			for (int j = 0; j < 3; j++)
			{
				string key = subject + "考试地点";
				key += int2string(j);
				cout << key <<":";
				SignInfoFactory::GetSignInfo(key);
			}
		}
		SignInfo* p_signinfo = SignInfoFactory::GetSignInfo("科目1考试地点1");
	}
};
//key值是唯一的,作者根据这个而建立对象
//通过唯一值访问对象

你可能感兴趣的:(生活)