单例模式(Singleton)

1、本质:控制实例数目

2、核心:

    1、构造方法私有

    2、类内部保存一个唯一引用

    3、提供一个获取类引用对象的静态方法

3、分类:

    1、懒汉式        --第一次使用时,创建实例对象   

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

    2、饿汉式        --装载类时,创建对象实例

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

3、优缺点:

    1、懒汉式:

      1、时间换空间

      2、延迟加载

      3、不加同步=线程不安全

    2、饿汉式:

      1、空间换时间

      2、线程安全

4、更好的解决方案:         --Lazy initialization holder class

 1 public class Singleton{
 2     /**
 3     * 私有化构造方法
 4     */
 5     private Singleton(){}
 6 
 7     /**
 8     * 静态内部类
 9     * 被调用时装载,从而实现了延时加载
10     */
11     public static class SingletonHolder{
12         private static Singleton instance = new Singleton();
13     }
14 
15     public static Singleton getInstance(){
16         return SingletonHolder.instance;
17     }
18 }

 

posted @ 2014-04-12 21:36  无名十四  阅读(154)  评论(0)    收藏  举报