Singleton 单例模式

设计模式的书籍:《设计模式 可复用面向对象软件的基础》

单例模式

  • 应用场景

    • 比如Factory
    • sping的
      首先构造方法为私有的

      饿汉模式

      1. public class Singleton{
      2. private static Singleton instance = new Singleton();
      3. //私有的构造方法
      4. private Singleton(){}
      5. public static Singleton getInstance(){
      6. return instance;
      7. }
      8. }

      懒汉模式

      DCL失效问题,因为JIT优化导致的指令重排,所以要加volatile,实现有序性和可见性。

      1. public class Singleton{
      2. private static volatile Singleton instance;
      3. private Singleton(){}
      4. public static Singleton getInstance(){
      5. if(instance==null){
      6. synchronzed(Singleton.Class){
      7. if(instance==null){
      8. instance = new Singleton();
      9. }
      10. }
      11. }
      12. return instance;
      13. }
      14. }

      但是加了volatile后,会拥有读写屏障,会使得该变量的读效率变低,我们只需要写屏障使得其不会重排序,故有以下修改

      1. public class Singleton{
      2. private static volatile Singleton instance;
      3. private Singleton(){}
      4. public static Singleton getInstance(){
      5. if(instance==null){
      6. synchronzed(Singleton.Class){
      7. if(instance==null){
      8. Singleton instance = new Singleton();
      9. //在此处添加写屏障,使得该处的指令不会重排序。
      10. Unsafe.getUnsafe().storeFence();
      11. Singleton.instance = instance;
      12. }
      13. }
      14. }
      15. return instance;
      16. }
      17. }

      静态内部类

      1. public class Singleton{
      2. private Singleton(){}
      3. private static class SingletonInstance{
      4. private static instance = new Singleton();
      5. }
      6. public static Singleton getInstance(){
      7. return SingletonInstance.instance;
      8. }
      9. }

      enmu

      1. enum singleton{
      2. INSTANCE;
      3. }