C++ 学习笔记(27)Flyweight Pattern

版权声明:如若转载,注明出处即可 https://blog.csdn.net/nishisiyuetian/article/details/82844041

Flyweight Pattern

享元模式

生活中的实例:(1)Word 等文档编辑器中,会出现很多的重复字母,例如“的”,“I”, "you"等,如果出现了 1000 次,就需要生成 1000 个对象(2)LOL 等近亲游戏中,小兵这一角色,数量极多,但它们其实有很多的共同点,不必生成那么多对象(3)围棋中,黑白棋子除了位置不一样,其他特征都是一样的,如果可以共享,就只需要两个实际存储的对象。

测试例子:

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

namespace Document {
	class Charactor {
	private:
		int x, y;
		int _size;
		int color;
		std::string symbol;
		// ...
	public:
		void display() const {
			std::cout << "位置  :  " << x << "  ,  " << y << std::endl;
			std::cout << "符号  :  " << symbol << std::endl;
			std::cout << "大小  :  " << _size << std::endl;
		}

		void setPos(const int _x, const int _y) {
			x = _x, y = _y;
		}

		void setSize(const int _Size) {
			_size = _Size;
		}

		void setColor(const int _color) {
			color = _color;
		}

		void setSymbol(const std::string _symbol) {
			symbol = _symbol;
		}
	} ;

	class Factory {
		using ptrType = std::shared_ptr<Charactor>;
	private:
		std::map<std::string, ptrType > factory;
	public:
		ptrType getSymbol(const std::string& symbol) {
			auto ans = factory.find(symbol);
			if( ans == factory.end() )
				factory.insert(std::make_pair(symbol, std::make_shared<Charactor>()));
			ans = factory.find(symbol);
			return ans->second;
		}
	};
}

int main() {
	using namespace Document;

	std::shared_ptr<Factory> factory = std::make_shared<Factory>();
	auto letter1 = factory->getSymbol("A");
	auto letter2 = factory->getSymbol("A");
	auto letter3 = factory->getSymbol("A");

	// 验证共享一个对象
	std::cout << letter1.get() << std::endl;
	std::cout << letter2.get() << std::endl;
	std::cout << letter3.get() << std::endl;

	// 实现同一对象, 不同体现
	std::cout << "\n\n-------------- letter1 -------------\n";
	letter1->setPos(3.5, 5);
	letter1->setSize(12);
	letter1->setSymbol("A");
	letter1->display();

	std::cout << "\n\n-------------- letter2 -------------\n";
	letter2->setPos(9, 8);
	letter2->setSize(24);
	letter2->setSymbol("B");
	letter2->display();
	return 0;
}

联想:单例模式,装饰者模式

猜你喜欢

转载自blog.csdn.net/nishisiyuetian/article/details/82844041