Java设计模式——单例模式(第3种为最终模式)
抛砖引玉 一:懒汉模式
/*
* 问题域:设计一个能且只能产生一个对象的类
*/
//单列模式一------懒汉模式
/*
* 1、它是一种预加载的实现。不管代码中有没有用到getInstance,都会被产生;
* 2、线程绝对安全的
*/
public class Singleton {
private static Singleton sin = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return sin;
}
}抛砖引玉 二:饿汉模式
//单列模式二-----饿汉模式
/*
* 1、延迟加载实现,只有在真正需要Singleton对象的时候才产生
* 2、不加同步,线程不安全;加同步,效率低
*/
public class Singleton {
private static Singleton sin;
private Singleton(){
}
public synchronized static Singleton getInstance(){
if(sin == null){
sin = new Singleton();
}
return sin;
}
}最终的--模式:单例模式 之双锁机制
//单列模式三---双锁机制
//既支持延迟加载,又支持线程安全的高并发
public class Singleton {
private static Singleton sin;
private Singleton(){
}
public static Singleton getInstance(){
if(sin == null){
synchronized(Singleton.class){
if(sin == null){
sin = new Singleton();
}
}
}
return sin;
}
}
Java单例模式详解
本文详细介绍了Java设计模式中的单例模式,包括懒汉模式、饿汉模式及双锁机制等三种实现方式,并探讨了它们在线程安全性及性能上的特点。
927

被折叠的 条评论
为什么被折叠?



