zoukankan      html  css  js  c++  java
  • 31天重构指南之二十九:去除中间人对象

    今天要说的重构来自于Folwers的重构目录,你可以在这里查看。

    有时在你的代码会存在一些幽灵类,Fowler称它们为“中间人”,中间人类除了调用别的对象之外不做任何事情,所以中间人类没有存在的必要,我们可以将它们从代码中删除。

       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: }
     
    要对上面的代码应用重构是简单明了的,我们只需要移除掉中间人对象就可以了。
       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: }

    原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/28/refactoring-day-29-remove-middle-man.aspx

  • 相关阅读:
    Filecoin:一种去中心化的存储网络(二)
    Filecoin:一种去中心化的存储网络(一)
    HTTP
    数据结构中的查找
    剑指offer-高质量的代码
    C++中STL容器的比较
    PBFT算法的相关问题
    springmvc最全约束
    springmvc入门(一)
    spring入门(一)
  • 原文地址:https://www.cnblogs.com/zhangronghua/p/1597289.html
Copyright © 2011-2022 走看看