当前位置:网站首页>[creation mode] single instance mode
[creation mode] single instance mode
2022-06-11 15:22:00 【Evader1997】
The singleton pattern
The singleton pattern , As the name suggests, it is a single instance . stay Java A class has only one instance ( object ), And the class provides access to the instance ( object ) Methods .
A question

Above, Java Two tool classes in ,Arrays Follow Collections. Students who have never been in contact with single cases , After looking at the picture above, there is no wave in my heart , Just look down . Students who have been in contact with single cases look at the following content with this question : The singleton pattern requires that a parameterless constructor be explicitly defined ,Arrays Follow Collections All have private nonparametric constructs , Why aren't they designed as singletons ?
Singleton pattern characteristics
- There is only one private parameterless constructor ( Look at the picture below, Xiaobai , The old driver jumped over )

- This class provides a method to get the singleton
Common singleton patterns
Hungry Chinese style ( Immediately load )
Hungry Chinese style , I remember it myself ‘ Urgent Han style ’, Association is reflected in urgency , You will instantiate the object first , This is what hunger actually means , Being in a hurry helps to remember .
public class HungrySingleton {
// Call the constructor to create the object as soon as it is defined
private static HungrySingleton singleton = new HungrySingleton();
private HungrySingleton() {
}
public HungrySingleton getSingleton() {
return singleton;
}
}
Slacker type ( Delay loading )
Lazy and hungry are opposite , Also belongs to the kind of not urgent , So the definition is not initialized immediately , It is initialized only when it is used . About the hungry Han style, this article only introduces the commonly used writing ( The specific reasons for this writing will be explored in the article ), Double check lock writing ( Perform two determinations on the declared singleton null operation , It means double inspection ).
public class LazySingeton {
private volatile static LazySingeton singeton;
private LazySingeton() {
}
public LazySingeton getSingeton() {
if (singeton == null) {
synchronized (LazySingeton.class) {
if (singeton == null) {
// Initialization only when used
singeton = new LazySingeton();
}
}
}
return singeton;
}
}
Application scenario of singleton mode
Generate a unique serial number
// Not applicable to distributed public class SingetonGenerator{ // serialize private long id; private static final SingetonGenerator singeton = new SingetonGenerator(); private SingetonGenerator(){ } public synchronized long next(){ return ++id; } public static SerialGenerator getInstance(){ return singeton; } }// Client calls public class SingetonGeneratorTest { public static void main(String[] args) { SingetonGenerator singeton = SingetonGenerator.getInstance(); // After executing this method id Will increase 1 singeton.next(); } }You need a shared data throughout the project
Many games can see xxx Players are online at the same time , For example, my youth , at that time 800 Ten thousand warriors are online at the same time . This 800 Wan is a shared data , Suppose this shared data is defined as a variable count, After the warrior logs in , You have to get the whole count Conduct +1 operation
Creating this object consumes a lot of resources , The most common is the database connection pool , Another example Mybatis establish SQLSessionFactory, How many does this factory need , Just one .
Class needs a large number of static methods , Static properties, etc ( This is actually the first question raised , To look down )
Static methods CF The singleton pattern (CF Representative comparison )
Please look again at the pictures at the beginning of the article and Singleton pattern characteristics , You'll find that Arrays And Collections Both have the first condition of singleton mode , There is only one private nonparametric construct , But neither of them has the second condition : This class provides a method to get the singleton . Why are these two classes not designed as singleton patterns ?
Say first conclusion , Static methods do not need to be changed , The singleton mode needs to be changed , How to understand that ? Be similar to Arrays,Collections For such tool classes, the variables and methods they declare are invariant ( Variable plus final), The singleton mode needs to provide a globally accessible node or data , It needs to change , For example, unique serial number , Number of people online , This cannot be done by static methods .
summary
Java Many tool classes in will also adopt the construction method of privatization to ensure the singleness of instances , But it is different from the single case , Tool classes do not save state , It contains only static methods or static properties , For developers to use , The singleton mode is stateful as mentioned above , It needs to change . Tool classes are just static methods , Static attribute , A singleton has a unique object instance !
The core of the singleton pattern is singleton , Single dog list , It only produces single ( One ) Objects . The two most common singleton patterns are lazy and hungry , In fact, the implementation of singleton mode is more than the two introduced in this article . For example, there are static internal class delay loading implementation singletons , Enumerating singletons, etc , It is recommended to select lazy or hungry people in combination with the use scenarios , Static inner classes and enumeration singletons are not recommended , Knowing that there are two ways .
边栏推荐
- 19. 二叉搜索树的插入删除修剪
- Hamad application layout scheme 02 of hashicopy
- Recyclerview usage record
- 【创建型模式】工厂方法模式
- Taking log4j as an example, how to evaluate and classify security risks
- Social software soul withdraws its IPO application: Tencent is a major shareholder
- Qualcomm WLAN framework learning (29) -- 6GHz overview
- After many years of digital transformation projects, the main architects are desperate: outsourcing should not have been used at the beginning!
- 腾讯面试官分享面试经验,如何考察面试者技术及个人综合素质,给正在面试的你一点建议
- 硬核分析懒汉式单例
猜你喜欢
[mysql_12] MySQL data types

Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos

Illustration of tiger international quarterly report: revenue of USD 52.63 million continued to be internationalized

Cisco Rui submitted the registration of sci tech Innovation Board: proposed to raise 600million yuan, with annual revenue of 222million yuan

Knowledge of affairs

Hebei huangjinzhai scenic spot adds "AED automatic defibrillator" to ensure the life safety of tourists!

Uniapp settings page Jump effect - navigateto switching effect - Global animationtype animation

Qualcomm WLAN framework learning (29) -- 6GHz overview

企业开发如何写出优雅的二级分类【美团小案例】

Learnopongl notes (IV) - Advanced OpenGL II
随机推荐
Hamad application layout scheme of hashicopy 01
线程实战入门【硬核慎入!】
Nexus of repository manager
19. insertion, deletion and pruning of binary search tree
How about art plus online school? Is it a new online organization?
企业开发如何写出优雅的二级分类【美团小案例】
Understanding of oauth2
多云安全合规扫描平台之RiskScanner
How to do well in we media? Did you do these steps right?
How to batch insert 100000 pieces of data
见微知著,细节上雕花:SVG生成矢量格式网站图标(Favicon)探究
深度剖析「圈组」关系系统设计 | 「圈组」技术系列文章
Backtracking / solution space tree permutation tree
China's technology goes to sea, tidb database's overseas exploration road | interview with excellent technical team
Talk about the principle of QR code scanning login
[SystemVerilog interface] ~ interface
[mysql_12] MySQL data types
Basic configuration command of Xinhua 3 switch system
回溯法/活动安排 最大兼容活动
MySQL用户权限总结【用户授权必会】