设计模式java----单例模式

时间:2022-04-21 15:24:06

一、懒汉式单例

在第一次调用的时候实例化自己,Singleton的唯一实例只能通过getInstance()方法访问、线程不安全

/**
* Created by Admin on 2017/3/19.
*/
public class Singleton {
private static Singleton instance;
private Singleton(){} public static Singleton getInstance() {
if(instance==null){
instance=new Singleton();
}
return instance;
}
}

解决方案:


  1. 在getInstance方法上加同步
/**
* Created by Admin on 2017/3/19.
*/
public class Singleton {
private static Singleton instance;
private Singleton(){} private static synchronized Singleton getInstance() {
if(instance==null){
instance=new Singleton();
}
return instance;
}
}

2.双重检查锁定

public class Singleton {
private static Singleton instance;
private Singleton(){} private static Singleton getInstance() {
if(instance==null){
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

3.3、静态内部类

这实现了线程安全,又避免了同步带来的性能影响

/**
* Created by Admin on 2017/3/19.
*/
public class Singleton {
private Singleton(){}
private static class singleLazy{
private static final Singleton instance=new Singleton();
} private static final Singleton getInstance() {
return singleLazy.instance;
}
}

二、饿汉式单例

饿汉式单例类.在类初始化时,已经自行实例化

/**
* Created by Admin on 2017/3/19.
*/
public class Singleton {
private Singleton(){}
private static final Singleton instance=new Singleton(); private static Singleton getInstance() {
return instance;
}
}