首页 > 其他 > 详细

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

时间:2017-02-09 11:34:16      阅读:175      评论:0      收藏:0      [点我收藏+]
  • 特点:整个应用中,单例类只存在一个对象
  • 场景:应用参数类等
  • 优点:节约内存,减少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 (){  
        
          }  
      }

       

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

原文:http://www.cnblogs.com/tylorliu/p/6380835.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!