享元模式

//享元模式(英语: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值