当前位置:网站首页>[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 .
边栏推荐
- JVM基础概念入门
- Basic configuration command of Xinhua 3 switch system
- Qcustomplot 1.0.1 learning (3) - plotting quadratic functions
- Mysql database optimization details
- Station B executives interpret the financial report: the epidemic has no impact on the company's long-term development, and the video trend is irresistible
- CNCF survey in 2021: a year for kubernetes to cross the gap
- How to batch insert 100000 pieces of data
- 【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器
- In June, 2019, cat teacher's report on monitoring
- 07 _ 行锁功过:怎么减少行锁对性能的影响?
猜你喜欢

3年亏损136亿,上市能救活威马吗?

What is excess product power? Find the secret key of the second generation cs75plus in the year of the tiger

Understanding of oauth2

LoveLive! Published an AI paper: generating models to write music scores automatically

腾讯面试官分享面试经验,如何考察面试者技术及个人综合素质,给正在面试的你一点建议

Devil cold rice # 037 devil shares the ways to become a big enterprise; Female anchor reward routine; Self discipline means freedom; Interpretation of simple interest and compound interest

Interview shock 26: how to stop threads correctly?

【SystemVerilog 之 接口】~ Interface

线程实战入门【硬核慎入!】

How to play seek tiger, which has attracted much attention in the market?
随机推荐
Hot seek tiger, a list of eco economic models
Learn more about and use ThreadLocal
See from the minute, carve on the details: Exploration of SVG generated vector format website icon (favicon)
Explain the kubernetes package management tool Helm
In June, 2019, cat teacher's report on monitoring
Nomad application layout scheme 04 of hashicopy (scaling and updating a job)
深度剖析「圈组」关系系统设计 | 「圈组」技术系列文章
Hashicopy之nomad应用编排方案04(伸缩及更新一个Job)
Exporting data using mysqldump
NVIDIA R & D director: how does AI improve chip design?
Qcustomplot 1.0.1 learning (3) - plotting quadratic functions
06 _ 全局锁和表锁 :给表加个字段怎么有这么多阻碍?
Flower shop window (linear DP)
China's technology goes to sea, tidb database's overseas exploration road | interview with excellent technical team
Qualcomm WLAN framework learning (29) -- 6GHz overview
07 _ Functions and disadvantages of row lock: how to reduce the impact of row lock on performance?
数据库优化
简单的C语言版本通讯录
How about art plus online school? Is it a new online organization?
How can local retail release the "imprisoned value" and make physical stores grow again?