Contents
  1. 1. 手写单例模式

手写单例模式

  • 懒汉式(不安全,有概率生成多个):在需要的时候去生成初始化一个静态的成员变量

    public class LazySingleton {
    private LazySingleton() {}
    private static LazySingleton instance = null;
    public static LazySingleton getInstance() {
    if (null == instance) {
    instance = new LazySingleton();
    }
    return instance;
    }
    }
  • 饿汉式(类的初始化期就生成一个实例,保证线程安全,缺点浪费内存,启动慢)

    private HungerSinleton(){}
    private static HungerSinleton instance = new HungerSinleton();
    public static HungerSinleton getInstance() {
    return instance;
    }
  • 双重锁式:节省不必要的内存的同时确保了只有一个(注意成员变量不需要用volatile修饰,因为HB原则,释放锁的时候会写回到主内存)

    private SyncSingleton(){}
    private static SyncSingleton instance = null;
    public static SyncSingleton getInstance() {
    if (null == instance) {
    synchronized(SyncSingleton.class) {
    if (null == instance) {
    instance = new SyncSingleton();
    }
    }
    }
    return instance;
    }
Contents
  1. 1. 手写单例模式