1、饿汉模式-单例
public class Singleton{
//私有化成员,初始化即创建实例,会造成不必要资源浪费
private static final Singleton instance = new Singleton();
//私有化构造方法
private Singleton(){};
//统一实例获取方法
public static 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;
}
}
3、加锁懒汉模式-单例
public class Singleton {
private static Singleton instance;
//私有化构造方法
private Singleton (){}
//统一实例获取方法,线程安全,重量锁,增加额外开销,效率低下
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
4、双重锁校验-单例
public class Singleton {
//volatile 保证内存可见性
private volatile static Singleton instance;
//私有化构造方法
private Singleton (){}
//统一实例获取方法
public static Singleton getSingleton() {
//第一次校验
if (instance == null) {
synchronized (Singleton.class) {
//第二次校验
if (instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
5、静态内部类-单例(推荐写法)
public class Singleton {
//静态内部类,私有成员
private static class SingletonFactory {
//线程安全,懒汉模式
private static final Singleton instance = new Singleton();
}
//私有化构造方法
private Singleton (){}
//统一实例获取方法
public static Singleton getInstance() {
return SingletonFactory.instance;
}
}
总结:
单例模式>>>同一时间内只会创建一个对象实例,大家共用该对象实例<<<<。
创建单例模式对象的要点:
1、静态私有成员对象
2、私有的构造方法
3、统一的获取实例方法
4、线程安全