《Head First设计模式》要点(四)

OO原则:(未完。。。)
    封装变化
    多用组合,少用继承
    针对接口编程,不针对实现编程
    为交互对象之间的松耦合设计而努力
    对扩展开放,对修改关闭
    依赖抽象,不要依赖具体类

OO模式:
    单件模式:
确保只有一个实例,并提供全局访问点。

要点:

     ·确保一个雷最多只有一个实例
    ·提供这个实例的全局访问点
    ·java中实现一个单件模式需要一个private constructor,一个static function,一个static instance varible
    ·如果使用多个类加载器,可能导致多个单件失效而产生多个实例

注意:

    单件模式在多线程情况下容易出现问题,可能产生不止一个实例

    解决方案有如下三种:

    1.同步getInstance()方法

public class Singleton {
    private static Singleton uniqueInstance;

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

     2.装载类时直接初始化

public class Singleton {
    private static Singleton uniqueInstance = new Singleton();

    private Singleton(){}
    
    public static synchronized Singleton getInstance() {
        return uniqueInstance;
}

     3.双重检查加锁,减少同步

public class Singleton {
    private volatile static Singleton uniqueInstance;

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


第一个方法效率比较低,第三个方法不适用于1.4以前的版本。

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值