软件设计重构秘笈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 {
}
总结
”去除中间人对象“很多时候都会很有作用,尤其是在误用设计模式的代码中最容易见到,
设计模式中的适配器模式和代理模式等都用中间的类是两者进行关联,这是比较合理的,
因为中间类做了很多事情,而对于没有任何作用的中间类应该移除。