重温设计模式(1)—— 单例模式

  • 特点:整个应用中,单例类只存在一个对象
  • 场景:应用参数类等
  • 优点:节约内存,减少GC消耗
  • 要点:私有化构造方法、线程安全
  • 实现方案:
    • 静态初始化:class被加载时生成单例对象
      public class SimpleSingleton {
          
          private SimpleSingleton(){        
          }
          private static SimpleSingleton instance = new SimpleSingleton();
          
          public static SimpleSingleton getInstance() {
              return instance;
          }
      }
    • 内部类
      public class InnerSingleton {
          
          private InnerSingleton(){
              
          }
          
          public static InnerSingleton getInstance(){
              return SingletonInstance.instance;
          }
          
          private static class SingletonInstance{
              
              static InnerSingleton instance = new InnerSingleton();
              
          }
      }
    • 枚举:可序列化、防反射
      public enum Singleton {  
        
          INSTANCE;  
        
          private Singleton (){  
        
          }  
      }

       

posted @ 2017-02-09 10:26  逝者如斯,随波逐流  阅读(113)  评论(0编辑  收藏  举报