使用枚举方式实现单例是很多优秀的开源代码中经常使用的方式,枚举类型不允许被继承,同样是线程安全且只能被实例化一次,但是枚举类型不能够懒加载,对 Singleton 主动使用,比如调用其中的静态方法则 INSTANCE 会立即得到实例化。
package singleton.singleton4;
public enum Singleton {
INSTANCE;
// 实例变量
private byte[] data = new byte[1024];
private static Singleton instance = null;
Singleton() {
System.out.println("INSTANCE will be initialized immediately");
}
public static void method() {
System.out.println("调用该方法主动使用单例");
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
Singleton.method();
new Thread(()->{
Singleton instance = Singleton.getInstance();
System.out.println(instance);
}).start();
new Thread(()->{
Singleton instance = Singleton.getInstance();
System.out.println(instance);
}).start();
}
}
INSTANCE will be initialized immediately
调用该方法主动使用单例
INSTANCE
INSTANCE
可对该代码实现懒加载特性,类似于 Holder 的方式,改进后的代码如下。
package singleton.singleton5;
public class Singleton {
// 实例变量
private byte[] data = new byte[1024];
private Singleton() {
System.out.println("+++++");
}
// 使用枚举充当 holder
private enum EnumHolder{
INSTANCE;
private Singleton instance;
EnumHolder(){
this.instance = new Singleton();
}
private Singleton getSingleton(){
return instance;
}
}
public static Singleton getInstance() {
return EnumHolder.INSTANCE.getSingleton();
}
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance);
}
}
+++++
singleton.singleton5.Singleton@7a81197d
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/124131253
内容来源于网络,如有侵权,请联系作者删除!