定义
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 SelectTraffic { public readonly ITraffic _trafficType; public SelectTraffic(ITraffic traffic) { _trafficType = traffic; } public void Drive() { _trafficType.Drive(); } }
调用
Console.WriteLine("策略模式"); SelectTraffic traffic = new SelectTraffic(new Car()); traffic.Drive(); traffic = new SelectTraffic(new Ship()); traffic.Drive(); traffic = new SelectTraffic(new AirPlane()); traffic.Drive();
标签:ITraffic,策略,SelectTraffic,Drive,模式,traffic,new,public From: https://www.cnblogs.com/daiwk/p/18108456