C++设计模式——享元模式(Flyweight)

享元模式

在软件系统采用对象方案解决问题在于大量细粒度的对象会充斥整个系统。而对象也有一定的开销。

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

#include<iostream>
#include<string>
#include<map>
using namespace std;

class Font {
private:
	string key;
public:
	Font(const string& str):key(str){}
	void operation() {
		cout << "flyweight  operate...." << key << endl;
	}
};

class FontFactory {
private:
	map<string, Font*> fontPool;//对象池
public:
	Font* GetFont(const string& key) {
		map<string, Font*>::iterator item = fontPool.find(key);
		if (item != fontPool.end())
			return fontPool[key];
		else{
			Font* font = new Font(key);
			cout << "create a new object!" << endl;
			fontPool[key] = font;
			return font;
		}
	}
};

int main()
{
	FontFactory* factory = new FontFactory();
	Font* font = factory->GetFont("hello");
	font->operation();
	//第二次执行时,无需再创建新的对象,直接使用对象池的对象
	factory->GetFont("hello")->operation();
	return 0;
}

结果如下:
在这里插入图片描述
要点:
享元模式主要是解决面向对象的代价问题,不解决抽象性问题。即保存创建好的对象,不重复创建相同的对象,节省内存开销。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dailingGuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值