分离职责

概念:本文中的“分离职责”是指当一个类有很多职责时,将部分职责分离到独立的类中。这样也符合面向对象的五大特征之中的一个的单一职责原则。同一时候也能够使代码的结构更加清晰,维护性更高。

 

正文:例如以下代码所看到的。Video类有两个职责。一个是处理video rental,还有一个是计算每一个客户的总租金。

我们能够将这两个职责分离出来,由于计算每一个客户的总租金能够在Customer计算。这也比較符合常理。

using System.Collections.Generic; 
using System.Linq; 

namespace LosTechies.DaysOfRefactoring.BreakResponsibilities.Before 

    public class Video 
   

        public void PayFee(decimal fee) 
        { 
        } 

        public void RentVideo(Video video, Customer customer) 
        { 
            customer.Videos.Add(video); 
        } 

        public decimal CalculateBalance(Customer customer) 
        { 
            returncustomer.LateFees.Sum(); 
        } 
    } 

    public class Customer 
   

        public IList<decimal> LateFees { getset; } 
        public IList<Video> Videos { getset; } 
    } 
}

重构后的代码例如以下,这样Video 的职责就变得非常清晰,同一时候也使代码维护性更好。

using System.Collections.Generic; 
using System.Linq; 

namespace LosTechies.DaysOfRefactoring.BreakResponsibilities.After 

    public class Video 
    

        public void RentVideo(Video video, Customer customer) 
        { 
            customer.Videos.Add(video); 
        } 
    } 

    public class Customer 
    

        public IList<decimal> LateFees { getset; } 
        public IList<Video> Videos { getset; } 

        public void PayFee(decimal fee) 
        { 
        } 

        public decimal CalculateBalance(Customer customer) 
        { 
            return customer.LateFees.Sum(); 
        } 
    } 
}

总结:这个重构常常会用到,它和之前的“移动方法”有几分相似之处,让方法放在合适的类中,而且简化类的职责,同一时候这也是面向对象五大原则之中的一个和设计模式中的重要思想。

原文地址:https://www.cnblogs.com/mfmdaoyou/p/7011116.html