软件设计重构秘笈29式-28去除中间人对象

软件设计重构秘笈29式-28去除中间人对象

概念

本文中的”去除中间人对象”是指把 在中间关联而不起任何其他作用的类移除,让有关系的两个类直接进行交互。

意图

有些时候在我们的代码会存在一些”幽灵类“,设计模式大师Fowler称它们为“中间人”类,
“中间人”类除了调用别的对象之外不做任何事情,所以“中间人”类没有存在的必要,我们可以将它们从代码中删除,从而让交互的两个类直接关联。
如下代码所示,Consumer 类要得到AccountDataProvider 的数据,但中间介入了没起任何作用的 AccountManager 类来关联,所以我们应当移除。

案例

public class Consumer {

    private AccountManager accountManager;

    public Consumer(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public Account get(int id) {
        return accountManager.getAccount(id);
    }

}

public class AccountManager {

    private AccountDataProvider accountDataProvider;

    public AccountManager(AccountDataProvider accountDataProvider) {
        this.accountDataProvider = accountDataProvider;
    }

    public Account getAccount(int id) {
        return accountDataProvider.getAccount(id);
    }

}

public class AccountDataProvider {

    public Account getAccount(int id)
    {
        // get account
        return null;
    }

}

public class Account {
}



重构

重构后的代码如下所示,Consumer 和AccountDataProvider 直接进行关联,这样代码就简单了。

public class Consumer {

    private AccountDataProvider accountDataProvider;

    public Consumer(AccountDataProvider accountDataProvider) {
        this.accountDataProvider = accountDataProvider;
    }

    public Account get(int id) {
        return accountDataProvider.getAccount(id);
    }

}

public class AccountDataProvider {

    public Account getAccount(int id)
    {
        // get account
        return null;
    }

}

public class Account {
}

总结

”去除中间人对象“很多时候都会很有作用,尤其是在误用设计模式的代码中最容易见到,
设计模式中的适配器模式和代理模式等都用中间的类是两者进行关联,这是比较合理的,
因为中间类做了很多事情,而对于没有任何作用的中间类应该移除。

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值