说明:
以下均为线程安全的实现方式。
懒汉、饿汉的非线程安全的意义不大,未实现。
1. 饿汉模式
类初始化时直接创建对象
public class Singleton {private static Singleton singleton = new Singleton();//饿汉模式,类初始化时直接创建public Singleton getInstance() {return singleton;}
}
2. 懒汉模式
懒汉模式,按需加载
public class Singleton {private Singleton singleton;public synchronized Singleton getInstance() {//懒汉模式,需要的时候再创建if(singleton == null) {singleton = new Singleton();}return singleton;}
}
3. 懒汉模式优化版
优化懒汉模式,减少锁的消耗
public class Singleton {private Singleton singleton;public Singleton getInstance() {if (singleton == null) {synchronized (singleton) {//懒汉模式,需要的时候再创建。double check,防止重复创建if(singleton == null) {singleton = new Singleton();}}}return singleton;}
}
4. 懒汉模式——无锁实现
利用静态内部类来实现
public class Singleton {//Singleton类无法继承private Singleton(){
// if(SingletonHolder.singleton == null) {
// throw new RuntimeException();
// }}private static class SingletonHolder {private static Singleton singleton = new Singleton();}public Singleton getInstance() {return SingletonHolder.singleton;}}
5. 枚举实现
利用枚举来实现,
public class Singleton {//Singleton类无法继承private Singleton(){}public static Singleton getInstance() {//返回内部enum的单例引用return SingletonEnum.INSTANCE.singleton;}private static enum SingletonEnum { INSTANCE;private Singleton singleton;private SingletonEnum() {singleton = new Singleton();}}public static void main(String[] args) {Singleton singleton = new Singleton();System.out.println(singleton);}
}