zoukankan      html  css  js  c++  java
  • 重构第5天:提升字段(Pull Up Field)

    理解:提升字段和前面讲解的方法提公很类似,可以说方式都是一样的。就是把继承类中经常用到的字段,提出来 放到基类中,达到通用的目的。提高代码重用性和可维护性。

    详解:如下重构前的代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysRefactor
     7 {
     8 
     9     public abstract class Account
    10     {
    11 
    12     }
    13 
    14     public class CheckingAccount : Account
    15     {
    16         private decimal _minimumCheckingBalance = 5m;
    17     }
    18 
    19     public class SavingsAccount : Account
    20     {
    21 
    22         private decimal _minimumCheckingBalance = 5m;
    23     }
    24 }

    从代码乐意看出,Account类的继承类CheckingAccount和SavingsAccount都有一个相同的字段_minimumCheckingBalance ,为了提高易用性和可维护性,我们把_minimumCheckingBalance 字段提出来放到基类Account中去。

    重构后的代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysRefactor
     7 {
     8 
     9     public abstract class Account
    10     {
    11         protected decimal _minimumCheckingBalance = 5m;
    12     }
    13 
    14     public class CheckingAccount : Account
    15     {
    16         
    17     }
    18 
    19     public class SavingsAccount : Account
    20     {
    21 
    22         
    23     }
    24 }

    注意提到公共基类中,最好用 protected 关键字来修饰,表示只能被自身和子类使用。重构其实就这么简单。

  • 相关阅读:
    axios+post获取并下载后台返回的二进制流
    vue+ckEditor5
    金额大写转换(改进版)
    vue+axios请求头封装
    移动端h5+vue失焦搜索,ios和android兼容问题
    vue滚动+滑动删除标记(移动端)仿qq/微信
    重置 centos 7 密码
    发现好玩的——github + git 有意思的用法
    github 中使用 issues
    java代理模式与装饰模式
  • 原文地址:https://www.cnblogs.com/yplong/p/5285427.html
Copyright © 2011-2022 走看看