单例模式
单例模式用来保证一个对象只能创建一个实例,它提供了对实例的全局访问方法;单例模式只由单个类组成,为确保单例实例的唯一性,所有的单例构造器都要被声明为私有的,并通过静态方法实现全局访问获得该实例。
public class Singleton {
private static Singleton instance;
private Singleton(){
System.out.println("单例模型被创建!");
}
public static Singleton getInstance(){
if(instance == null)
instance = new Singleton();
return instance;
}
public void doSomething(){
System.out.println("doSomething!");
}
}
我们通过调用Singleton.getInstance();获得单例对象
在getInstance方法中,通过条件判断确保实例只会被创建一次
同步锁单例模式
在多线程中使用单例模式可能会出错。如果线程为空,可能有两个线程同时调用getInstance,第一个线程使用构造器实例化单例对象,当单例对象还未实例化,第二个线程检查实例为空,也会开始实例化单例对象。
通过给getInstance加同步锁解决问题
向getInstance方法的声明中添加synchronized关键字保证线程安全
public class Singleton {
private static Singleton instance;
private Singleton(){
System.out.println("单例模型被创建!");
}
public static synchronized Singleton getInstance(){
if(instance == null)
instance = new Singleton();
return instance;
}
public void doSomething(){
System.out.println("doSomething!");
}
}
使用synchronized代码块实现
public class Singleton {
private static Singleton instance;
private Singleton(){
System.out.println("单例模型被创建!");
}
public static Singleton getInstance(){
synchronized(Singleton .class){
if(instance == null)
instance = new Singleton();
}
return instance;
}
public void doSomething(){
System.out.println("doSomething!");
}
}
同步锁能够保证线程安全,但带来了延迟,使用双重校验锁机制的同步锁单例模式
public class Singleton {
private static Singleton instance;
private Singleton(){
System.out.println("单例模型被创建!");
}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton .class){
if(instance == null)
instance = new Singleton();
}
}
return instance;
}
public void doSomething(){
System.out.println("doSomething!");
}
}
无锁的线程安全单例模式
通过在声明时直接实例化静态成员的方法来确保一个类只有一个实例
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){
System.out.println("单例模型被创建!");
}
public static synchronized Singleton getInstance(){
return instance;
}
public void doSomething(){
System.out.println("doSomething!");
}
}