设计模式(3)--对象结构(6)--享元

2023-12-20 13:51:11
1. 意图

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

2. 三种角色

? ? 抽象享元(Flyweight)、具体享元(Concrete Flyweight)、具体不共享元(UnShared Concrete Flyweight)、享元工厂(Flyweight Factory)

3. 优点

? ? 3.1 节省空间,共享越多,节省越大

4. 缺点

? ? 4.1 增加了运行时开销?

5. 相关模式?

? ? 5.1 享元模式通常和组合模式结合,用共享叶节点的有向无环图实现一个逻辑上的层次结构

? ? 5.2 通常,最好用享元实现State和Strategy对象。?

6. 代码示意(C++)
#pragma once
#include <iostream>
#include <string>
#include <map>
using namespace std;

class Flyweight
{
protected:
	string m_strName;
public:
	Flyweight(const string& strName) {
		m_strName = strName;
	}
	virtual void operation(int extrinsicState) = 0;
};
class SharedFlyweight :public Flyweight
{
	int intrinsicState;
public:
	SharedFlyweight() :Flyweight("shared"), intrinsicState(2) {
	}
	virtual void operation(int extrinsicState) {
		cout << "I am " << m_strName << endl;
		cout << "ExtrinsicState is " << extrinsicState << endl;
		cout << "IntrinsicState is " << this->intrinsicState << endl;
	}
};
class UnsharedFlyweight :public Flyweight
{
	int m_allState;
public:
	UnsharedFlyweight() :Flyweight("unshared"), m_allState(3) {

	}
	virtual void operation(int extrinsicState) {
		cout << "I am " << m_strName << endl;
		cout << "ExtrinsicState is " << extrinsicState << endl;
		cout << "AllState is " << this->m_allState << endl;
	}
};
class FlyweightFactory
{
	map<string, Flyweight*> m_mapFlyweights;
public:
	~FlyweightFactory() {
		for (auto& pair : m_mapFlyweights) {
			delete pair.second;
		}
		m_mapFlyweights.clear();
	}
	Flyweight* GetFlyweight(const string& name) {
		auto it = m_mapFlyweights.find(name);
		if (it != m_mapFlyweights.end()) {
			cout << "Found shared flyweight" << endl;
			return it->second;
		}
		Flyweight* pFlyweight = 0;
		if (name == "shared") {
			pFlyweight = new SharedFlyweight();
			m_mapFlyweights.emplace(make_pair(name, pFlyweight));
			cout << "Create a shared flyweight" << endl;
		}
		else {
			cout << "Not a shared flyweight" << endl;
		}
		return pFlyweight;
	}

	Flyweight* GetUnsharedFlyweight() {
		return new UnsharedFlyweight();
	}
};
#include "Flyweight.h"
int main() {
	FlyweightFactory* pFactory = new FlyweightFactory();
	Flyweight* pFlyweight = pFactory->GetFlyweight("shared");
	if (0 != pFlyweight) {
		pFlyweight->operation(0);
	}
	pFlyweight = pFactory->GetFlyweight("shared");
	if (0 != pFlyweight) {
		pFlyweight->operation(1);
	}

	pFlyweight = pFactory->GetFlyweight("unshared");
	if (0 == pFlyweight) {
		pFlyweight = pFactory->GetUnsharedFlyweight();
		pFlyweight->operation(1);
		delete pFlyweight;
	}

	delete pFactory;
	return 0;
}

运行结果:

6.1 第二次使用SharedFlyweight时从map里取出,而不需要重新创建(3.1)

6.2 Flyweight不强制共享,比如UnsharedFlyweight

?

文章来源:https://blog.csdn.net/myepicure/article/details/134909223
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。