定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点
使用场景
通常使用在创建需要花费较大资源的对象上,如Hibernate中SessionFactory这样的重量级对象
入门案例:
代码:
饿汉式:
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}
懒汉式:
public class Singleton2 {
private static Singleton2 singleton = null;
private Singleton2(){}
public static Singleton2 getInstance(){
if(singleton == null){
singleton = new Singleton2();
}
return singleton;
}
}
懒汉式-多线程:
public class Singleton3 {
private static Singleton3 singleton = null;
private Singleton3(){}
//注意这是synchronized用得是类锁不是this
public static synchronized Singleton3 getInstance(){
if(singleton == null){
singleton = new Singleton3();
}
return singleton;
}
}
懒汉式-多线程-双重判断(高效):
public class Singleton4 {
private static Singleton4 singleton = null;
private Singleton4(){}
public static Singleton4 getInstance(){
if(singleton == null){
synchronized (Singleton4.class){
if(singleton == null){
singleton = new Singleton4();
}
}
}
return singleton;
}
}