C++ 享元模式(Flyweight)

简介

运用共享技术有效地支持大量细粒度对象的复用。

优点

由于不需要重新创建对象,减少了初始化对象的开销提高运行速度,而且新建对象也是需要占用内存的,从而也减小内存消耗。
由于对对象复用,从而减小代码量和系统复杂度。

使用场景

当一个应用程序使用了大量的对象,对象的大多数状态都可变为外部状态,

代码如下:


#include <iostream>
#include <string>
#include <memory>
#include <map>


class flyweight 
{
public:
	flyweight(std::string key) : m_key(key)
	{
	}
 
	virtual void operate(int value)
	{
		std::cout << "flyweight::operate : m_key["<< m_key <<"] value[" << value << "] ."<< std::endl;
	}
 
private:
	std::string m_key;
};
 

class flyweight_factory
{
public:
	flyweight_factory(void)
	{
	}
 
	~flyweight_factory(void)
	{
		std::map<std::string, flyweight *>::iterator it;
		for (it = m_flymap.begin(); it != m_flymap.end(); it++)
		{
			if (it->second != NULL)
			{
				delete it->second;
				it->second = NULL;
			}
		}
	}
	
public:
	flyweight *get_flyweight(std::string key)
	{
		std::map<std::string, flyweight *>::iterator it = m_flymap.find(key);
		if (it != m_flymap.end())
		{
			return it->second;
		}
	 
		flyweight * fly = new flyweight(key);
		m_flymap.insert(std::map<std::string, flyweight *>::value_type(key, fly));
	 
		return fly;
	}

private:
	std::map<std::string, flyweight *> m_flymap;
};

int main()
{
	std::cout << "start-up .." << std::endl;
	
	
	std::shared_ptr<flyweight_factory>  ff = std::make_shared<flyweight_factory>();
 
	flyweight * f1 = ff->get_flyweight("lanpang");
	flyweight * f2 = ff->get_flyweight("naja");
	flyweight * f3 = ff->get_flyweight("lanpang");
	flyweight * f4 = ff->get_flyweight("lanpang");
 
	f1->operate(100);
	
	f2->operate(111);
	
	f3->operate(133);
 
	f4->operate(200);

	std::cout << "done .." << std::endl;
    return 0;
}


运行如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值