设计模式之单例模式

来源:互联网 发布:现货电子交易软件 编辑:程序博客网 时间:2024/06/06 02:21
  1. 基本概念
    单例模式指的是:对于某一个类,整个程序中值存在一个该类的实例对象。常见的比如数据库连接对象等。

  2. 代码示例,单例模式的几种写法及优劣

/** * 饿汉式写法,多线程下不能保证对象的确定性**/public class SingletonHungryUnsec {    private static SingletonHungryUnsec instance;    private SingletonHungryUnsec() {    }    /**     * 饿汉式,且线程不安全     * @return instancce     */    public static SingletonHungryUnsec getInstance (){        if (null == instance) {            instance = new SingletonHungryUnsec();        }        return instance;    }}实际操作时,不推荐这样的写法。
public class SingletonHungrySec {    private static SingletonHungrySec instance;        private SingletonHungrySec() {    }   /***         * 饿汉式,线程安全型         * @return instance         */        public static SingletonHungrySec getInstance () {            if (null == instance) {                synchronized (SingletonHungrySec.class) {                    if (null == instance) {                        instance = new SingletonHungrySec();                    }                }            }            return instance;        }}

以上这种写法,通过synchronized关键字,在创建实例对象时,进行双重校验,确保了对象的唯一性。
当然,也可以在方法的定义上加synchrozied关键字,只是多了不必要的同步,每次getInstance()时,都需要加锁解锁操作。

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

上面这样的写法是饱汉式,即在声明属性的时候已经创建了实例对象,后续程序中只需要调用获取即可,但是这种方式并没有达到lazy loader的效果。

0 0
原创粉丝点击