设计模式之单例模式

  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值