29. 去除中间人对象

资料参考:https://blog.csdn.net/knightswarrior/article/details/9447815

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

正文:有些时候在我们的代码会存在一些“幽灵类”,设计模式大师Fowler称它们为“中间人”类,“中间人”类除了调用别的对象之外不做任何事情,所以“中间人”类没有存在的必要,我们可以将它们从代码中删除,从而让交互的两个类直接关联。

如下代码所示,Consumer 类要得到AccountDataProvider 的数据,但中间介入了没起任何作用的 AccountManager 类来关联,所以我们应当移除

 1 /**
 2  * 消费者类
 3  */
 4 class Comsumer {
 5     private final AccountManager accountManager;
 6 
 7     public Comsumer(AccountManager accountManager) {
 8         this.accountManager = accountManager;
 9     }
10 
11     /**
12      * 获取账号
13      *
14      * @param id 账号标识id
15      */
16     public void get(int id) {
17         Account account = accountManager.getAccount(id);
18     }
19 }
 1 /**
 2  * 账号管理类
 3  */
 4 class AccountManager {
 5     private final AccountDataProvider accountDataProvider;
 6 
 7     public AccountManager(AccountDataProvider accountDataProvider) {
 8         this.accountDataProvider = accountDataProvider;
 9     }
10 
11     /**
12      * 获取账号
13      *
14      * @param id 账号标识id
15      * @return 账号
16      */
17     public Account getAccount(int id) {
18         return accountDataProvider.getAccount(id);
19     }
20 }
 1 /**
 2  * 账号数据提供者
 3  */
 4 class AccountDataProvider {
 5     /**
 6      * 获取账号
 7      *
 8      * @param id 账号标识id
 9      * @return 账号
10      */
11     public Account getAccount(int id) {
12         return new Account(id);
13     }
14 }
 1 /**
 2  * 账号
 3  */
 4 class Account {
 5     private final int id;
 6 
 7     public Account(int id) {
 8         this.id = id;
 9     }
10 }

重构后的代码如下所示,Consumer 和AccountDataProvider 直接进行关联,这样代码就简单了。
 1 /**
 2  * 消费者类
 3  */
 4 class Comsumer {
 5     private final AccountDataProvider accountDataProvider;
 6 
 7     public Comsumer(AccountDataProvider accountDataProvider) {
 8         this.accountDataProvider = accountDataProvider;
 9     }
10 
11     /**
12      * 获取账号
13      *
14      * @param id 账号标识id
15      */
16     public void get(int id) {
17         Account account = accountDataProvider.getAccount(id);
18     }
19 }
 1 /**
 2  * 账号数据提供者
 3  */
 4 class AccountDataProvider {
 5     /**
 6      * 获取账号
 7      *
 8      * @param id 账号标识id
 9      * @return 账号
10      */
11     public Account getAccount(int id) {
12         return new Account(id);
13     }
14 }
 1 /**
 2  * 账号
 3  */
 4 class Account {
 5     private final int id;
 6 
 7     public Account(int id) {
 8         this.id = id;
 9     }
10 }

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

原文地址:https://www.cnblogs.com/ys99/p/14205328.html