zoukankan      html  css  js  c++  java
  • 抽象类和开闭原则

      public class Vehicle
        {
            public void Stop() {
    
                Console.WriteLine("Stopped");
            }
            /// <summary>
            /// 这不符合开闭原则
            /// </summary>
            /// <param name="type"></param>
            public void Run(string type)
            {
                if(type == "car")
                {
                    Console.WriteLine("Car is running");
                }
                else if (type == "Truck")
                {
                    Console.WriteLine("Truck is running");
                }
            }
        }
    
        public class Truck:Vehicle {
    
            public void Run()
            {
                Console.WriteLine("Truck is running");
            }
        }
    
        public class Car:Vehicle
        {
            public void Run() {
                Console.WriteLine("Car is running");
            }
        }
     public class Vehicle
        {
            public void Stop() {
    
                Console.WriteLine("Stopped");
            }
          
            public virtual void Run()
            {
                Console.WriteLine("Vehicle is running"); 
            }
        }
    
        public class Truck:Vehicle {
    
            public override void Run()
            {
                Console.WriteLine("Truck is running");
            }
        }
    
        public class Car:Vehicle
        {
            public override void Run()
            {
                Console.WriteLine("Car is running");
            }
        }

    但是我们发现Vehicle这个类永远不会去调用run这个方法因为不符合逻辑也很模糊

     abstract public class Vehicle
        {
            public void Stop()
            {
    
                Console.WriteLine("Stopped");
            }
    
            public abstract void Run();
    
        }
    
        public class Truck : Vehicle
        {
    
            public override void Run()
            {
                Console.WriteLine("Truck is running");
            }
        }
    
        public class Car : Vehicle
        {
            public override void Run()
            {
                Console.WriteLine("Car is running");
            }
        }
    
        public class RaceCar : Vehicle
        {
            public override void Run()
            {
                Console.WriteLine("RaceCar is running");
            }
        }

    添加赛车类不会修改原本的类,之需要修改原本的类就可以了

  • 相关阅读:
    与客服聊天功能测试点
    京东优惠券如何测试
    Linux笔试题
    线程与线程池原理
    PyCharm 介绍、安装、入门使用
    银行APP测试用户体验性方面
    python的闭包
    列表解析2
    深入函数
    再谈装饰器@@@
  • 原文地址:https://www.cnblogs.com/-alvin/p/10925452.html
Copyright © 2011-2022 走看看