抽象类和开闭原则

  public class Vehicle
    {
        public void Stop() {

            Console.WriteLine("Stopped");
        }
        /// 
        /// 这不符合开闭原则
        /// 
        /// 
        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");
        }
    }

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

 

你可能感兴趣的:(抽象类和开闭原则)