zoukankan      html  css  js  c++  java
  • 代码重构之下降方法

    核心:该方法和提升方法刚好相反,提升方法核心是将复用的方法提升到基类中,或是转移到接口中去,下降方法的核心则是将类的特有方法放在所属类的内部。

        这样使得类仅有自己该有的功能,也可以减少一些不必要的内存开销。

    还是延用上篇中手机的例子,摇一摇可以进行编辑内容的删除这个功能只有IPhone手机有,而Galaxy手机不具备,那这个功能就是IPhone所特有的功能,那么该方法就不能像发送短信一样被写在基类Phone中,而是只能放在IPhone类中。

    【类中的字段重构同理】

    代码演示:

    1、基类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace PushDownMethod
    {
        public abstract class Phone
        {
            public void Call()
            {
                Console.WriteLine("打电话");
            }
            public void SendMsg()
            {
                Console.WriteLine("发送消息");
            }
        }
    }
    View Code

    2、子类一

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace PushDownMethod
    {
        public class IPhone:Phone
        {
            /// <summary>
            /// 该子类特有的方法
            /// </summary>
            public void ShakeDeleteEditMsg() {
                Console.WriteLine("摇一摇删除编辑的内容~~");
            }
        }
    }
    View Code

    3、子类二

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace PushDownMethod
    {
        public class Galaxy:Phone
        {
        }
    }
    View Code

    4、客户端

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    /// <summary>
    /// 下降方法
    /// </summary>
    namespace PushDownMethod
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                IPhone iPhone = new IPhone();
                iPhone.Call();
                iPhone.SendMsg();
                iPhone.ShakeDeleteEditMsg(); //只有IPhone才有的方法
                Galaxy galaxy = new Galaxy();
                galaxy.Call();
                galaxy.SendMsg();
                Console.ReadKey();
                
            }
        }
    }
    View Code

    结果展示:

    写写博客,方便自己也方便需要的人~~

  • 相关阅读:
    python 文件批量改名重命名 rename
    AN INTEGER FORMULA FOR FIBONACCI NUMBERS
    python opencv cv2 imshow threading 多线程
    adb shell 查看当前与用户交互的 activity
    sublime text build system automatic ctrl/cmd+B自动选择 python2 或 python3
    pip 源的问题
    Mac 安装 Android commandlinetools 各种报错的问题
    GIMP 一键均匀添加多条参考线 一键均匀切分图片
    Shell 脚本如何输出帮助信息?
    raspberry pi 配置
  • 原文地址:https://www.cnblogs.com/Yisijun/p/13218272.html
Copyright © 2011-2022 走看看