31天重构学习笔记14. 分离职责

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

正文:如下代码所示,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/ywsoftware/p/2892594.html