单例模式 singleton

2020-03-10  本文已影响0人  MisAutumn
  1. 饿汉模式,类加载到内存后就实例化一个类
    pros:JVM线程安全,JVM只load一个类到内存一次,static是class加载之后马上加载的
    cons:不用也实例化
public class Manager {
  private static final Manager INSTANCE = new Manager();
  private Manager() {}
  // private static final Manager INSTANCE
  // static {
  //    INSTANCE = new Manager();
  //}
  
  public static Manager getInstance {
    return INSTANCE;
  }
}
  1. 懒加载
    pros:需要时才加载
    cons:多线程访问有影响
    可以给方法加syncronized解决,但带来效率下降
public class Manager {
  private static Manager INSTANCE;
  private Manager() {}
  
  public static Manager getInstance {
    if(INSTANCE == null) {
      Instance = new Manager();
    } 
    return INSTANCE;
  }
}
public class Manager01 {
    private static Manager01 INSTANCE;
    private Manager01() {}

    public static Manager01 getInstance() {
        if (INSTANCE == null) { // 判断没有一体化,相当于没加锁
            synchronized (Manager01.class) {
                INSTANCE = new Manager01();
            }
        }
        return INSTANCE;
    }
}

没缺点了:双重检查

public class Manager02 {
    private static Manager02 INSTANCE;
    private Manager02() {}

    public static Manager02 getInstance() {
        if (INSTANCE == null) { // 双重判断
            synchronized (Manager01.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Manager02();
                }
            }
        }
        return INSTANCE;
    }
}
  1. 静态内部类:最完美的
public class Manager03 {
    private Manager03() {}
    private static class Manager03Holder { // 类加载时不会被初始化
        private final static Manager03 INSTANCE = new Manager03();
    }
    
    public Manager03 getInstance() {
        return Manager03Holder.INSTANCE; // 加载静态内部类
    }
}
上一篇下一篇

猜你喜欢

热点阅读