标签:oid running run veh abs override code 逻辑 bsp
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"); } }
添加赛车类不会修改原本的类,之需要修改原本的类就可以了
标签:oid running run veh abs override code 逻辑 bsp
原文地址:https://www.cnblogs.com/-alvin/p/10925452.html