• 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(); 
            } 
        } 
    }

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

  • 相关阅读:
    远程服务器Xshell的使用 -- 重启服务器操作 和 linux的常用命令
    Spring Boot 服务端开发项目目录结构
    font-weight字体重量和font-family字体类型中的粗细度的对应关系
    iframe的使用
    js 多个箭头函数的使用
    js 获取本地上传的文件(图片和视频)的宽高和大小
    react-navigation Modal弹出层中的StackNavigator导航如何和物理返回匹配?
    IntelliJ IDEA 2019.3的安装和激活
    android EditText 的聚焦和失焦,输入框的监听
    Android 系统架构 和 各个版本代号介绍
  • 原文地址:https://www.cnblogs.com/ywsoftware/p/2892594.html
Copyright © 2020-2023  润新知