IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之十四:分离职责

Posted on 2009-09-29 15:43  张荣华  阅读(341)  评论(0编辑  收藏  举报

当一个类有许多职责时,将部分职责分离到独立的类中可以更好的遵守“类的单一职责原则”,使用“分享职责”这个重构非常简单,让我们来看下面的代码:

   1: public class Video
   2: {
   3:     public void PayFee(decimal fee)
   4:     {
   5:     }
   6:  
   7:     public void RentVideo(Video video, Customer customer)
   8:     {
   9:         customer.Videos.Add(video);
  10:     }
  11:  
  12:     public decimal CalculateBalance(Customer customer)
  13:     {
  14:         return customer.LateFees.Sum();
  15:     }
  16: }
  17:  
  18: public class Customer
  19: {
  20:     public IList<decimal> LateFees { get; set; }
  21:     public IList<Video> Videos { get; set; }
  22: }
我们可以看到Video类有两个职责,一个是处理video rental,另一个是计算每个客户的总租金。我们可以将这两个职责分离到两个独立类中,重构后的代码如下所示:
   1: public class Video
   2: {
   3:     public void RentVideo(Video video, Customer customer)
   4:     {
   5:         customer.Videos.Add(video);
   6:     }
   7: }
   8:  
   9: public class Customer
  10: {
  11:     public IList<decimal> LateFees { get; set; }
  12:     public IList<Video> Videos { get; set; }
  13:  
  14:     public void PayFee(decimal fee)
  15:     {
  16:     }
  17:  
  18:     public decimal CalculateBalance(Customer customer)
  19:     {
  20:         return customer.LateFees.Sum();
  21:     }
  22: }
 
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/14/refactoring-day-14-break-responsibilities.aspx