zoukankan      html  css  js  c++  java
  • 重构第29天 去除中间人对象(Remove Middle Man)

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

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

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

     1 public class Consumer
     2     {
     3         public AccountManager AccountManager { get; set; }
     4 
     5         public Consumer(AccountManager accountManager)
     6         {
     7             AccountManager = accountManager;
     8         }
     9 
    10         public void Get(int id)
    11         {
    12             Account account = AccountManager.GetAccount(id);
    13         }
    14     }
    15 
    16     public class AccountManager
    17     {
    18         public AccountDataProvider DataProvider { get; set; }
    19 
    20         public AccountManager(AccountDataProvider dataProvider)
    21         {
    22             DataProvider = dataProvider;
    23         }
    24 
    25         public Account GetAccount(int id)
    26         {
    27             return DataProvider.GetAccount(id);
    28         }
    29     }
    30 
    31     public class AccountDataProvider
    32     {
    33         public Account GetAccount(int id)
    34         {
    35             // get account
    36         }
    37     }

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

     1  public class Consumer
     2     {
     3         public AccountDataProvider AccountDataProvider { get; set; }
     4 
     5         public Consumer(AccountDataProvider dataProvider)
     6         {
     7             AccountDataProvider = dataProvider;
     8         }
     9 
    10         public void Get(int id)
    11         {
    12             Account account = AccountDataProvider.GetAccount(id);
    13         }
    14     }
    15 
    16     public class AccountDataProvider
    17     {
    18         public Account GetAccount(int id)
    19         {
    20             // get account
    21         }
    22     }
  • 相关阅读:
    css3线性渐变
    php的%s
    面向对象
    excel导入导出
    保存Excel
    保存word
    图片预览
    验证日期输入格式
    级联菜单
    中级前端知识点提要
  • 原文地址:https://www.cnblogs.com/yplong/p/5381455.html
Copyright © 2011-2022 走看看