当前位置:网站首页>Enjoy element mode (flyweight)
Enjoy element mode (flyweight)
2022-06-26 13:06:00 【baboon_ chen】
Reference resources :
Xiangyuan design mode (refactoringguru.cn)
The flyweight pattern ( Detailed Edition ) (biancheng.net)
One 、 What is the sharing mode ?
Definition : By sharing the same state shared by multiple objects , Allows you to load more objects in a limited amount of memory .
You need to split the data members of the class into two parts : Internal state 、 External state . The inside is fixed , External is adjustable data . For unchanging intrinsic information , Can be stored in a shared way , This reduces memory usage .
such as , Black and white pieces in go and Gobang , The position of the pieces on the chessboard changes , Color is fixable . So only two pieces need to be stored : The spots 、 An albino . The impact point can be stored in a two-dimensional matrix . Registration of vehicle information in traffic police system , Vehicle information can be divided into internal states ( brand 、 model 、 Color )、 External state ( Belong to 、 License plate ).

Two 、 Example
Enjoying yuan (Flyweight) The pattern includes the following main characters :
- Abstract enjoyment (Flyweight): It is the base class of all the concrete primitive classes , The public interface that needs to be implemented for the specific membership specification , The external state of the non sharer is passed in as a parameter through the method .
- Enjoy the specific yuan (Concrete Flyweight): Implement the interface specified in the abstract membership role .
- Non enjoyment yuan (Unsharable Flyweight) : It's an external state that can't be shared , It is injected into the relevant methods of the specific sharer in the form of parameters .
- The flyweight factory (Flyweight Factory): Responsible for creating and managing the shareware roles . When a client object requests a sharing object , Check whether there are qualified sharing objects in the system , If it exists, provide it to the customer ; If it doesn't exist , Create a new share object .
- The customer's role is to obtain the specific enjoy yuan through enjoy yuan factory , And visit the specific methods of sharing .

1、 Vehicle management system ( Vehicle information registration )
/**
* Flyweight Design Pattern
*
* By sharing common parts of state among multiple objects , Instead of saving all the data in each object , Allows you to put more objects into the available RAM in .
* The example shows a police car management system , The shared information of each car is ( brand 、 model 、 Color ), Unshared information includes ( Belong to 、 License plate ).
*/
#include <iostream>
#include <string>
#include <unordered_map>
// Sharing status ( Internal state )
struct SharedState
{
std::string brand_; // brand
std::string model_; // model
std::string color_; // Color
SharedState(const std::string &brand, const std::string &model, const std::string &color)
: brand_(brand), model_(model), color_(color)
{
}
friend std::ostream &operator<<(std::ostream &os, const SharedState &ss)
{
return os << "[ " << ss.brand_ << " , " << ss.model_ << " , " << ss.color_ << " ]";
}
};
// Unshared state ( External state )
struct UniqueState
{
std::string owner_; // Belong to
std::string plates_; // License plate
UniqueState(const std::string &owner, const std::string &plates)
: owner_(owner), plates_(plates)
{
}
friend std::ostream &operator<<(std::ostream &os, const UniqueState &us)
{
return os << "[ " << us.owner_ << " , " << us.plates_ << " ]";
}
};
/**
* Enjoying yuan (Flyweight) Class contains the state shared in the original object .
* The same meta object can be used in many different scenarios .
* The state stored in the element is called “ Internal state ”. The state passed to a method of enjoyment is called “ External state ”.
*/
class Flyweight
{
private:
SharedState *shared_state_;
public:
Flyweight(const SharedState *shared_state) : shared_state_(new SharedState(*shared_state))
{
}
Flyweight(const Flyweight &other) : shared_state_(new SharedState(*other.shared_state_))
{
}
~Flyweight()
{
delete shared_state_;
}
SharedState *shared_state() const
{
return shared_state_;
}
void Operation(const UniqueState &unique_state) const
{
std::cout << "Flyweight: Displaying shared (" << *shared_state_ << ") and unique (" << unique_state << ") state.\n";
}
};
/**
* The flyweight factory (Flyweight Factory) It will manage the existing cache pool .
* With the factory , The client does not need to create the share element directly , They simply call the factory and pass it some internal state of the target share .
* The factory will look up the previously created shares according to the parameters , If you find a share that meets the criteria, it is returned , If it is not found, create a new share according to the parameters .
*/
class FlyweightFactory
{
private:
// disorder map Containers do not need to be sorted ,hash lookup .
std::unordered_map<std::string, Flyweight> flyweights_;
std::string GetKey(const SharedState &ss) const
{
return ss.brand_ + "_" + ss.model_ + "_" + ss.color_;
}
public:
FlyweightFactory(std::initializer_list<SharedState> share_states)
{
for (const SharedState &ss : share_states)
{
this->flyweights_.insert(std::make_pair<std::string, Flyweight>(this->GetKey(ss), Flyweight(&ss)));
}
}
// If you don't have one, you can create one , If you have, you can reuse the existing shared elements
Flyweight GetFlyweight(const SharedState &shared_state)
{
std::string key = this->GetKey(shared_state);
if (this->flyweights_.find(key) == this->flyweights_.end())
{
std::cout << "FlyweightFactory: Can't find a flyweight, creating new one.\n";
this->flyweights_.insert(std::make_pair(key, Flyweight(&shared_state)));
}
else
{
std::cout << "FlyweightFactory: Reusing existing flyweight.\n";
}
return this->flyweights_.at(key);
}
// Print meta cache
void ListFlyweights() const
{
size_t count = this->flyweights_.size();
std::cout << "\nFlyweightFactory: I have " << count << " flyweights:\n";
for (std::pair<std::string, Flyweight> pair : this->flyweights_)
{
std::cout << pair.first << "\n";
}
}
};
// client , By transmission key Get Xiangyuan from Xiangyuan factory .
// Record the vehicle information to the public security vehicle management database
void AddCarToPoliceDatabase(
FlyweightFactory &ff, const std::string &plates, const std::string &owner,
const std::string &brand, const std::string &model, const std::string &color)
{
std::cout << "\nClient: Adding a car to database.\n";
const Flyweight &flyweight = ff.GetFlyweight({brand, model, color});
flyweight.Operation({owner, plates});
}
int main()
{
// The client code usually creates a bunch of pre populated during the initialization phase of the application flyweights.
FlyweightFactory *factory = new FlyweightFactory({
{"Chevrolet", "Camaro2018", "pink"}, {"Mercedes Benz", "C300", "black"}, {"Mercedes Benz", "C500", "red"}, {"BMW", "M5", "red"}, {"BMW", "X6", "white"}});
factory->ListFlyweights();
AddCarToPoliceDatabase(*factory,
"CL234IR",
"James Doe",
"BMW",
"M5",
"red");
AddCarToPoliceDatabase(*factory,
"CL234IR",
"James Doe",
"BMW",
"X1",
"red");
factory->ListFlyweights();
delete factory;
return 0;
}
3、 ... and 、 Advantages and disadvantages , Applicable scenario
advantage
- If there are many similar objects in the program , Then you can save a lot of memory .
shortcoming
- You may need to sacrifice execution speed in exchange for memory , Because others need to recalculate part of the scenario data every time they call the share element method .
- To make objects shareable , You need to externalize some states that you can't share , This will increase the complexity of the program .
边栏推荐
- 享元模式(Flyweight)
- 国标GB28181协议EasyGBS级联宇视平台,保活消息出现403该如何处理?
- F - Charm Bracelet
- 倍福PLC通过程序获取系统时间、本地时间、当前时区以及系统时间时区转换
- Angle de calcul POSTGIS
- Adobe Acrobat prevents 30 security software from viewing PDF files or there are security risks
- [esp32-c3][rt-thread] run RT-Thread BSP minimum system based on esp32c3
- 软件测试报告应该包含的内容?面试必问
- 倍福TwinCAT3实现CSV、TXT文件读写操作
- System tasks (display / print class) in Verilog - $display, $write, $strobe, $monitor
猜你喜欢

Echart堆叠柱状图:色块之间添加白色间距效果设置

Explain C language 10 in detail (C language series)

This function has none of deterministic, no SQL solution

P5733 【深基6.例1】自动修正

倍福将EtherCAT模块分到多个同步单元运行--Sync Units的使用

What are the common categories of software testing?

Processsing function random

5月产品升级观察站

Beifu PLC passes MC_ Readparameter read configuration parameters of NC axis

倍福PLC基于NT_Shutdown实现控制器自动关机重启
随机推荐
解中小企业之困,百度智能云打个样
mariadb学习笔记
国标GB28181协议EasyGBS级联宇视平台,保活消息出现403该如何处理?
倍福通过CTU和TON实现时间片大小和数量的控制
Solution of Splunk iowait alarm
KVM 显卡透传 —— 筑梦之路
Detailed explanation of C const: definition and use of C constant
Electron official docs series: Testing And Debugging
Electron official docs series: Development
I - Dollar Dayz
What should the software test report include? Interview must ask
[esp32-C3][RT-THREAD] 基于ESP32C3运行RT-THREAD bsp最小系统
Dark horse notes - Common APIs
code force Party Lemonade
Electron official docs series: Contributing
C - Common Subsequence
国标GB28181协议EasyGBS视频平台TCP主动模式拉流异常情况修复
Unit practice experiment 8 - using cmstudio to design microprogram instructions based on basic model machine (1)
【网络是怎么连接的】第二章(中):一个网络包的发出
Learning Processing Zoog