抽象类和开闭原则

Posted -alvin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了抽象类和开闭原则相关的知识,希望对你有一定的参考价值。

  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");
        }
    }

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

 

以上是关于抽象类和开闭原则的主要内容,如果未能解决你的问题,请参考以下文章

DAO 模式和开闭原则

设计模式之美——单一职责原则和开闭原则

依赖倒转原则

依赖抽象,而不要依赖具体实现

6大设计原则之开闭原则

面向对象几大原则