当前位置:网站首页>Enumeration class implements singleton mode
Enumeration class implements singleton mode
2022-07-27 05:23:00 【Master yuan】
List of articles
1. The singleton pattern
I believe everyone is familiar with the singleton mode , Here is an example of using enumeration classes to implement the singleton pattern .
1.1 Hungry Han style single case mode
public class YYSingletonDemo {
private YYSingleton() {
}
private enum YYSingleton {
INSTANCE;
}
public static YYSingleton getInstance() {
return YYSingleton.INSTANCE;
}
}
1.2 Lazy singleton pattern
public class YYSingleton {
private YYSingleton() {
}
private enum YYSingletonHolder {
INSTANCE;
private YYSingleton instance = null;
private YYSingleton getYYSingleton() {
instance = new YYSingleton();
return instance;
}
}
public static YYSingleton getInstance() {
return YYSingletonHolder.INSTANCE.instance;
}
}
2. Why is using enum classes thread safe singleton mode ?
Due to the particularity of enumeration classes , Ensure the uniqueness of enumeration types . Because the enumeration class will be loaded at compile time , Therefore, it belongs to the starving Han style singleton mode . But if you treat it as a member variable , Only when in use will it be loaded , It belongs to lazy singleton mode .
边栏推荐
猜你喜欢

JVM Part 1: memory and garbage collection part 10 - runtime data area - direct memory

pytorch 数据类型 和 numpy 数据 相互转化

File processing (IO)

2021 OWASP top 4: unsafe design

JVM Part 1: memory and garbage collection part 14 -- garbage collector

Li Kou achieved the second largest result

Database design - relational data theory (ultra detailed)

JVM Part 1: memory and garbage collection part 11 -- execution engine

JVM Part 1: memory and garbage collection part 6 -- runtime data area local method & local method stack

JVM上篇:内存与垃圾回收篇九--运行时数据区-对象的实例化,内存布局与访问定位
随机推荐
redis事务
The difference between strlen and sizeof
牛客剑指offer--JZ12 矩阵中的路径
弹球小游戏
JVM Part 1: memory and garbage collection part 14 -- garbage collector
LeetCode之268.Missing number
学生管理系统
MQ set expiration time, priority, dead letter queue, delay queue
ssm框架整合
Machine learning overview
JVM上篇:内存与垃圾回收篇十四--垃圾回收器
JVM上篇:内存与垃圾回收篇二--类加载子系统
Integrate SSM
Database connection pool & Druid usage
Find the number of combinations (the strongest optimization)
What should test / development programmers over 35 do? Many objective factors
MQ FAQ
JVM上篇:内存与垃圾回收篇九--运行时数据区-对象的实例化,内存布局与访问定位
Quoted popular explanation
听过最自律的一句话: 那些我难以言表 不作声响