zoukankan      html  css  js  c++  java
  • 与继承相关的一些重构(二)

    5.提取主类:提取一个基类,抽象出共有方法,比较常用的重构,这里的基类也许并不存在,需要自己新建立。

     用法场景:当有一个类中的某个方法需要经常被其他的类调用的时候,说明这个方法重用率很高,可以考虑把它抽象出来,放到一个基类中。

    //重构前
    publicclass Dog
    {
      
    publicvoid EatFood()
      {
        
    // eat some food
      }

      
    publicvoid Groom()
      {
        
    // perform grooming
      }
    }
    //重构后
    publicclass Animal
    {
      
    publicvoid EatFood()
      {
        
    // eat some food
      }

      
    publicvoid Groom()
      {
        
    // perform grooming
      }
    }
    publicclass Dog : Animal
    {
    }

    6.提取子类:将基类中的方法放到子类中,这里的子类也许并不存在,需要自己新建立。

     用法场景:当基类中的某些方法并不是面向所有或者大多数类的时候,需要把这些方法下放到子类中。

    //重构前
    publicclass Registration
    {
      
    public NonRegistrationAction Action { get; set; }
      
    publicdecimal RegistrationTotal { get; set; }
      
    publicstring Notes { get; set; }
      
    publicstring Description { get; set; }
      
    public DateTime RegistrationDate { get; set; }
    }
    //重构后
    publicclass Registration
    {
      
    publicdecimal RegistrationTotal { get; set; }
      
    publicstring Description { get; set; }
      
    public DateTime RegistrationDate { get; set; }
    }

    publicclass NonRegistration : Registration
    {
      
    public NonRegistrationAction Action { get; set; }
      
    publicstring Notes { get; set; }
    }

    7.合并继承:把子类合并到基类中去。

     用法场景:当子类只有属性定义,并且这些属性可以放置在基类中,那这个子类就是多余的,在把属性和基类合并后就可以移除了。

    //重构前
    publicclass Website
    {
      
    publicstring Title { get; set; }
      
    publicstring Description { get; set; }
      
    public IEnumerable<Webpage> Pages { get; set; }
    }
    publicclass StudentWebsite : Website
    {
      
    publicbool IsActive { get; set; }
    }
    //重构后
    publicclass Website
    {
      
    publicstring Title { get; set; }
      
    publicstring Description { get; set; }
      
    public IEnumerable<Webpage> Pages { get; set; }
      
    publicbool IsActive { get; set; }
    }

      继承相关的重构就这几点,尝试在项目中多用用,很快就有感觉了:)

  • 相关阅读:
    【转】如何复制一个正在使用的文件?(VB6.0)
    VB6.0操作SQL Server——增删改查
    SQL Server时间戳并发 .
    WCF WinCE 中 手机端 非字符串型 datetime,int,decimal,double 等等 传递不到WCF端的解决方案
    VB中调用带参数存储过程的实现(数据库)
    C# VB6.0 Java C++ GUID 生成
    vb6.0 取得文件扩展名
    VB6.0 取得windows 临时目录 temp
    VB6.0 在代码中直接调用 文件打开对话框,不使用windows控件
    VB数据库记录查询四法
  • 原文地址:https://www.cnblogs.com/ywsoftware/p/2892648.html
Copyright © 2011-2022 走看看