Flyweight mode of design mode (C++)

Author: Zhai Tianbao Steven
Copyright statement: The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source

1. What is Flyweight Mode?

       Flyweight mode is a structural software design mode. By sharing objects, memory usage can be reduced as much as possible, so as to achieve the purpose of optimization.

       Just like playing mahjong, there are 10 tables playing at the same time, and each table has 4 "eight cylinders". If you create 40 "eight cylinders" objects, it will be very redundant, but if you use the Flyweight mode to create a set of mahjong tiles , when each table plays "Batong", the "Batong" in Flyweight is called, which is equivalent to using only one object, which not only saves resources, but also fulfills the requirements.

       In the above example, the table number and brand number are the external states of the Flyweight mode, such as A1 Batong, which is the first "Batong" of table A, A and 1 are the external state; and the card "Batong" itself It is the internal state, and the internal content can be shared. The extrinsic content changes with the environment, takes up much less resources, and is often just a simple data structure.

       Advantages of flyweight mode:

  1. Reduce waste of resources. Shared resources greatly reduce the resource consumption of the system.
  2. Improve system operating efficiency. When resources are overused, system efficiency can suffer greatly.

      Disadvantages of flyweight mode:

  1. Maintaining shared objects requires additional overhead.
  2. Increased system complexity. To run Flyweight, in addition to internal and external states, there are also threads that must be fully considered.

2. Flyweight mode

2.1 Structure diagram

       The client is the Main function, which calls the flyweight factory to obtain the flyweight object.

2.2 Code example

       Scene description: Simulate combining a set of gossip cards.

//Flyweight.h
/****************************************************/
#pragma once
#include <iostream>
#include <unordered_map>
#include <vector>
#include <list>

using namespace std;

// 抽象享元
class Flyweight 
{
public:
	// 操作
	virtual void operation() = 0;

};

// 具体享元
class ConcreteFlyweight : public Flyweight 
{
public:
	// 构造函数
	ConcreteFlyweight(string name) : m_name(name) {}

	// 操作
	virtual void operation() {
		cout << "打出" << m_name << endl;
	}

private:
	string m_name;
};

// 享元工厂
class FlyweightFactory 
{
public:
	// 析构函数
	~FlyweightFactory() {
		for (auto it : flyweights) {
			cout << "销毁" << it.first << "牌" << endl;
			delete it.second;
			it.second = nullptr;
		}
		flyweights.clear();
	}

	// 获取享元
	Flyweight* getFlyweight(string name) {
		// 若没有,则创建
		if (flyweights.find(name) == flyweights.end()) {
			cout << "创建" << name << "牌" << endl;
			flyweights[name] = new ConcreteFlyweight(name);
		}
		else {
			cout << "已有" << name << "牌" << endl;
		}
		return flyweights[name];
	}

private:
	std::unordered_map<string, Flyweight*> flyweights;
};
//main.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Flyweight.h"

using namespace std;

int main()
{
	FlyweightFactory *factory = new FlyweightFactory();
	Flyweight* f1 = factory->getFlyweight("乾");
	Flyweight* f2 = factory->getFlyweight("坤");
	Flyweight* f3 = factory->getFlyweight("坎");
	Flyweight* f4 = factory->getFlyweight("离");
	Flyweight* f5 = factory->getFlyweight("震");
	Flyweight* f6 = factory->getFlyweight("巽");
	Flyweight* f7 = factory->getFlyweight("艮");
	Flyweight* f8 = factory->getFlyweight("兑");
	Flyweight* f9 = factory->getFlyweight("坤");
	f3->operation();
	delete factory;
	factory = nullptr;
	return 0;
}

       The program results are as follows.

       The eight cards of the gossip are created because they do not exist when they are called for the first time, and the existing Kun is called for the ninth time, so new is not used. After deleting the factory, don't forget to delete the new data in the destructor.

3. Summary

       I try my best to express my understanding of Flyweight mode with more popular words and intuitive code routines. There may be some things that are not thoughtful. If you have different opinions, welcome to communicate in the comment area! I hope the examples I gave can help you better understand the Flyweight pattern.

       If the article helps you, you can give me a like to let me know, I will be very happy ~ come on!

Guess you like

Origin blog.csdn.net/zhaitianbao/article/details/129986811