1、懒汉式——线程不安全
public class SingletonOne {public static SingletonOne singleton;private SingletonOne() {}public static SingletonOne getSingleton() {if (singleton == null)return new SingletonOne();return singleton;}}
懒汉式实现了懒加载,但是线程不安全,基本不会使用。
2、懒汉式——线程安全
public class SingletonTwo {public static SingletonTwo singleton;private SingletonTwo() {}public static synchronized SingletonTwo getSingleton() {if (singleton == null)return new SingletonTwo();return singleton;}}
在第一种的基础上加了个synchronized,保证线程安全,同时实现了懒加载,只是效率不高。
3、饿汉式
public class SingletonThree {public static SingletonThree singleton = new SingletonThree();private SingletonThree () { }public static SingletonThree getSingleton() {return singleton;}}
由于实例优先提供,不存在线程安全问题,但是没有实现懒加载。
4、饿汉式——变种
public class SingletonFour {public static SingletonFour singleton;static {singleton = new SingletonFour();}private SingletonFour () { }public static SingletonFour getSingleton() {return singleton;}}
其实和之前的一样,仅仅是将单例的创建挪到了静态块。
5、静态内部类式
public class SingletonFive {private static class SingletonHolder {private static SingletonFive singleton = new SingletonFive();}private SingletonFive () {}public static final SingletonFive getSingleton(){return SingletonHolder.singleton;}}
静态内部类保证了懒加载,单例实例优先提供又保证了线程安全性,较实用。
6、枚举式
public enum SingletonSix {SINGLETON;}
枚举的天然特性保证了单例,天然的私有构造器,天然的线程安全性,未被大规模使用的原因是枚举出现的有点晚。
7、双重校验锁式
public class SingletonSeven {private static volatile SingletonSeven singleton;private SingletonSeven() {}public static SingletonSeven getSingleton(){if (singleton == null) {synchronized (SingletonSeven.class) {if (singleton == null)return new SingletonSeven();}}return singleton;}}
注意:
- volatile的使用,为了防止暴露一个未初始化的不完整单例实例;
- 双重判空校验,第一个判断避免了频繁的加锁,第二个判断可以拦住多余的创建实例的线程;
- 加锁,保证了线程安全(只有一个实例)
这种实现方式是经常出现在面试题中的,而且经常会要求手写。
