大话设计模式——单例模式

来源:互联网 发布:acl 软件 编辑:程序博客网 时间:2024/09/21 06:17

单例模式:保证一个类又且仅有一个实例,并且提供一个访问他的全局访问点。

理解:保证只有一个实例;

      提供一个得到实例的的方法;

实现:类的构造方法私有;提供一个公共的得到实例的方法。

懒汉式:


 

恶汉式:


懒汉式和恶汉式的区别是:恶汉式在自己被加载的时候就将自己实例化,而懒汉式是在自己第一次被引用的时候才实例化。

懒汉式的多线程问题:

方法一:在getInstance加上synchronized

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

方法二:

双重锁定

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

方法三:

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