码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2016-03-28 18:47:30      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

1、私有化构造器,不能直接创建,调用方法创建对象;

  

    public class Singleton {  
        private static Singleton instance;  
        private Singleton (){}  
      
        public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
        }  
    }  

2、饿汉式:instance在类装载时就实例化

    public class Singleton {  
        private static Singleton instance = new Singleton();  
        private Singleton (){}  
        public static Singleton getInstance() {  
        return instance;  
        }  
    }  

3、静态内部类:

  

    public class Singleton {  
        private static class SingletonHolder {  
          private static final Singleton INSTANCE = new Singleton();  
        }  
        private Singleton (){}  
        public static final Singleton getInstance() {  
          return SingletonHolder.INSTANCE;  
        }  
    }  

 

单例模式

标签:

原文地址:http://www.cnblogs.com/zilanghuo/p/5330023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!