代码重构之下降方法

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

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

还是延用上篇中手机的例子,摇一摇可以进行编辑内容的删除这个功能只有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

结果展示:

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

原文地址:https://www.cnblogs.com/Yisijun/p/13218272.html