单例算是最简单的设计模式了,用途自不用多说,但是写好单例也是比较考验一个程序猿功底的,这就是为什么很多面试官乐于让面试者写一写单例的原因,正所谓简约而不简单。废话不多说,下面就用java来实现各种各样的单例吧。
1.饿汉模式
public class Singleton{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
2.懒汉模式
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
return instance;
}
return instance;
}
}
3.线程安全的单例模式
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
return instance;
}
return instance;
}
}
4.双检的线程安全的单例模式
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized{
if(instance == null){
instance = new Singleton();
return instance;
}
}
}
return instance;
}
}
5.最牛逼的线程安全的写法
public class Singleton{
private Singleton(){}
private class SingletonHolder{
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
public static Singleton getInstance(){
return SingletonHolder.getInstance();
}
}
时间: 2024-10-07 22:08:32