抽象类和开闭原则
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"); } }
添加赛车类不会修改原本的类,之需要修改原本的类就可以了
以上是关于抽象类和开闭原则的主要内容,如果未能解决你的问题,请参考以下文章