策略模式
定义
public interface ITraffic { void Drive(); } public class Car : ITraffic { public void Drive() { Console.WriteLine("车在陆地行驶"); } } public class Ship : ITraffic { public void Drive() { Console.WriteLine("船在水上行驶"); } } public class AirPlane : ITraffic { public void Drive() { Console.WriteLine("飞机在天上飞"); } } public class ErrorTraffic : ITraffic { public void Drive() { Console.WriteLine("选择错误"); } } public class TrafficConfig { private ITraffic? _trafficType; public static readonly Dictionary<string, ITraffic> trafficsMap = new Dictionary<string, ITraffic>() { { "car",new Car()}, { "ship",new Ship()}, { "air",new AirPlane()} }; //无法去掉 public TrafficConfig(ITraffic traffic) { _trafficType = traffic; } //去掉IF ELSE public TrafficConfig(string trafficCode) { _trafficType = trafficsMap.GetValueOrDefault(trafficCode); } public void Drive() { _trafficType?.Drive(); } }
调用
var code = "car"; //if (code == "car") //{ // TrafficConfig traffic = new TrafficConfig(new Car()); //} //else if (code == "ship") //{ // TrafficConfig traffic = new TrafficConfig(new Ship()); //} //else if (code == "air") //{ // TrafficConfig traffic = new TrafficConfig(new AirPlane()); //} //traffic.Drive(); TrafficConfig traffic = new TrafficConfig(code); traffic.Drive();
喜欢 C#、SQL、Web