当前位置:网站首页>枚举类实现单例模式
枚举类实现单例模式
2022-07-27 05:01:00 【圆师傅】
1. 单例模式
单例模式相信大家都不陌生,这里提供一个使用枚举类实现单例模式的例子。
1.1 饿汉式的单例模式
public class YYSingletonDemo {
private YYSingleton() {
}
private enum YYSingleton {
INSTANCE;
}
public static YYSingleton getInstance() {
return YYSingleton.INSTANCE;
}
}
1.2 懒汉式单例模式
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.为什么使用枚举类是线程安全的单例模式?
由于枚举类的特殊性,保证了枚举类型的唯一性。由于枚举类会在编译时期进行加载,因此属于是饿汉式的单例模式。但是如果把它当作一个成员变量,只有在使用时才会加载,属于懒汉式单例模式。
边栏推荐
猜你喜欢
随机推荐
JVM上篇:内存与垃圾回收篇五--运行时数据区-虚拟机栈
During its low-level period, this slave edge causes the instruction number to make a corresponding model
Use of file i/o in C
35. Scroll
JVM上篇:内存与垃圾回收篇三--运行时数据区-概述及线程
Domestic mainstream ERP software market
Acceptance and neglect of events
传智教育|软件测试工程师未来的发展方向有哪些?
B1025 反转链表*******
集合框架的使用
JDBC API 详解
[optical flow] - data format analysis, flowwarp visualization
Create datasource using Druid connection pool
Introduction to Kali system ARP (network disconnection sniffing password packet capturing)
TypeScript 详解
JVM Part 1: memory and garbage collection part 10 - runtime data area - direct memory
Mysql表的约束
老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破
What should test / development programmers over 35 do? Many objective factors
[untitled] I is circularly accumulated under certain conditions. The condition is usually the length of the loop array. When it exceeds the length, the loop will stop. Because the object cannot judge









