单例模式
懒汉模式
public class Singleton{
private Singleton
(){};
private static Singleton singleton
=null
;
public static Singleton
getInstance()
{
if(singleton
==null
){ singleton
=new Singleton();}
return singleton
;
}
}
恶汉模式
public class Singleton
{
private Singleton
(){};
private static Singleton singleton
=new Singleton();
public static Singleton
getinstance()
{
return singleton
;
}
}
实现方式1线程安全的单例模式(对 getinstance 方法加锁)
public class Singleton{
private Singleton(){};
private static Singleton singleton
=null
;
public static synchronized Singleton
getInstance()
{
if(singleton
==null
){
singleton
=new Singleton();
}
return singleton
;
}
}
实现方式 2:双重检查锁定:对 getinstance 方法加锁+if 判断
public class Singleton{
public static Singleton
getInstance() {
if (singleton
== null
) {
synchronized (Singleton
.class) {
if (singleton
== null
) {
singleton
= new Singleton();
}
}
}
return singleton
;
}
}
}
实现方法3:静态内部类
public class Singleton {
private static class LazyHolder {
private static final Singleton INSTANCE
= new Singleton();
}
private Singleton
(){}
public static final Singleton
getInstance() {
return LazyHolder
.INSTANCE
;
}
}
(这种比上面1、2都好一些,既实现了线程安全,又避免了同步带来的性能影响。)
转载请注明原文地址:https://tech.qufami.com/read-18269.html