当前位置:网站首页>Creation mode - singleton mode
Creation mode - singleton mode
2022-06-21 12:11:00 【attempt_ to_ do】
1. Pattern motivation
For some classes in the system , Only one example is important , for example , There can be multiple print tasks in a system , But there can only be one task at work ; A system can only have one window manager or file system ; A system can only have one timing tool or ID( Serial number ) generator .
How to ensure that a class has only one instance and that the instance is easy to access ? Defining a global variable ensures that objects can be accessed at any time , But it doesn't prevent us from instantiating multiple objects .
A better solution is to have the class itself responsible for keeping its only instance . This class ensures that no other instance is created , And it can provide a way to access the instance . This is the motivation of the singleton model .
2. Pattern definition
The singleton pattern (Singleton Pattern): Singleton pattern ensures that a class has only one instance , And instantiate it yourself and provide it to the entire system , This class is called a singleton class , It provides methods for global access .
There are three main points of the singleton model : One is that a class can only have one instance ; Second, it must create this instance by itself ; Third, it must provide the whole system with this instance by itself . The singleton pattern is an object creation pattern . Singleton mode is also known as singleton mode or singleton mode .
3. Pattern structure

4. Sequence diagram

5. The code analysis
5.1.c++ Realization
#include "Singleton.h"
#include <iostream>
using namespace std;
Singleton * Singleton::instance = NULL;
Singleton::Singleton(){
}
Singleton::~Singleton(){
delete instance;
}
Singleton* Singleton::getInstance(){
if (instance == NULL)
{
instance = new Singleton();
}
return instance;
}
void Singleton::singletonOperation(){
cout << "singletonOperation" << endl;
}
#include <iostream>
#include "Singleton.h"
using namespace std;
int main(int argc, char *argv[])
{
Singleton * sg = Singleton::getInstance();
sg->singletonOperation();
return 0;
}
5.2.Golang Realization
package singleton
type singleton map[string]string
var (
once sync.Once
instance singleton
)
func New() singleton {
once.Do(func() {
instance = make(singleton)
})
return instance
}
s := singleton.New()
s["this"] = "that"
s2 := singleton.New()
fmt.Println("This is ", s2["this"])
// This is that
6. Pattern analysis
The purpose of singleton pattern is to ensure that a class has only one instance , And provide a global access point to access it . The singleton pattern contains only one role , It's a singleton class ——Singleton. Singleton classes have a private constructor , Make sure users can't get through new Keyword instantiates it directly . besides , This pattern contains a static private member variable and a static public factory method , The factory method is responsible for verifying the existence of instances and instantiating itself , Then it's stored in a static member variable , To ensure that only one instance is created .
In the implementation of the singleton pattern , Three points need to be noted :
- The constructor of the singleton class is private ;
- Provide a static private member variable of its own ;
- Provide a public static factory method .
7. Apply to the environment
The singleton mode can be used in the following cases :
- The system only needs one instance object , If the system requires a unique serial number generator , Or you need to consider that the resource consumption is too large and only one object is allowed to be created .
- Only one common access point is allowed for a single instance of a client call class , In addition to the public access point , The instance cannot be accessed by any other means .
- The singleton pattern should be used when a class has only one instance in a system . In turn, , If a class can have several instances coexisting , We need to improve the singleton mode , Make it a multiple model
边栏推荐
猜你喜欢

Illustrated with pictures and texts -- wechat applet to obtain the user's geographic location information and call Tencent map API to obtain the user's specific location

Use huggingface to quickly load pre training models and datasets in the moment pool cloud
![[Harbin Institute of technology] information sharing for the first and second examinations of postgraduate entrance examination](/img/06/df5a64441814c9ecfa2f039318496e.jpg)
[Harbin Institute of technology] information sharing for the first and second examinations of postgraduate entrance examination

Travel does not heal the soul

The final battle of the giant: instant retailing

WPF 使用 MAUI 的自绘制逻辑

Is 100W data table faster than 1000W data table query?

i.MX - RT1052 SDCard操作(SDIO接口)

Snow Ice City (blackened)

巨头局终战:即时零售
随机推荐
PCB电路板设计都有哪些注意事项?
Is the Huatai Securities account given by qiniu school true? Is it safe to open an account
[comprehensive pen test] difficulty 2.5/5: "tree array" and "double tree array optimization"
2022 safety officer-b certificate retraining question bank and simulated examination
The final battle of the giant: instant retailing
Compilation de l'environnement vs Code + GCC développé par stm32
蜜雪冰城(已黑化)
STL basic container test
Quantitative research on heterogeneous communities 4 rate of change with bands
广东发产品检测券,消费者也有份
uniapp中常用到的方法(部分) - 时间戳问题及富文本解析图片问题
channels详细使用说明
ACM. HJ36 字符串加密 ●●
External-Attention-tensorflow(更新中)
Guangdong issues product testing coupons, and consumers also share
2022 HV electrician judgment questions and answers
动手学数据分析 数据可视化
看懂UML类图和时序图
Codeworks round 797 (Div. 3) F. shifting string problem solution
harmonyos培训一