设计模式之单例

来源:互联网 发布:mac如何重装 编辑:程序博客网 时间:2024/06/01 14:01

code address:

http://download.csdn.net/detail/kaikai_sk/9872762

单例模式的意义

有些对象我们只需要一个:线程池、缓存、硬件设备等
如果多个实例会有造成冲突、结果的不一致性等问题
是否可以用静态变量方式来实现?
或者程序员之间协商个全局变量?
单例模式:确保一个类最多只有一个实例,并提供一个全局访问点

类图

这里写图片描述

实现

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

一个巧克力工厂的例子

package Factory;import simple.Singleton;public class ChocolateFactory{    private boolean empty;    private boolean boiled;    private static ChocolateFactory uniqueInstance;    private ChocolateFactory()    {    }    public static ChocolateFactory getInstance()    {        if(uniqueInstance==null)        {            uniqueInstance=new ChocolateFactory();        }        return uniqueInstance;    }    public void fill()    {        if(empty)        {            //添加原料动作            empty=false;            boiled=false;        }    }    public void boil()    {        if(!empty && !boiled)        {            //煮沸            boiled =true;        }    }    public void drain()    {        if(!empty && boiled)        {            //倒出巧克力            empty=true;        }    }}

经典单例模式的优化

  1. 多线程问题
    优化:
    同步(synchronized)getInstance方法
    public static synchronized ChocolateFactory getInstance()     {        if (uniqueInstance == null)         {                    uniqueInstance = new ChocolateFactory();            }        }        return uniqueInstance;    }

“急切”创建实例

public static ChocolateFactory uniqueInstance = new ChocolateFactory ();

双重检查加锁

public volatile static ChocolateFactory uniqueInstance = null;    public static ChocolateFactory getInstance() {        if (uniqueInstance == null) {            synchronized (ChocolateFactory.class) {                if (uniqueInstance == null) {                    uniqueInstance = new ChocolateFactory();                }            }        }        return uniqueInstance;    }