用多态替换条件
3中交通工具
public class Car : Vehicle { public int AmountOfFuelNeededToFillTank() { return 12; } } public class Airplane : Vehicle { public int AmountOfFuelNeededToFillLeftFuelTank() { return 3; } public int AmountOfFuelNeededToFillRightFuelTank() { return 4; } } public class Boat : Vehicle { public int AmountOfFuelNeededToFillFrontFuelTank() { return 8; } public int AmountOfFuelNeededToFillRearFuelTank() { return 10; } }
检查加油车路线上所有车辆以确定要在该加油车内装多少燃料
public class FuelingStation { public int AddFuelToTruck(List<Vehicle> vehiclesOnRoute) { var amountOfFuelToLoadOnTruck=0; foreach(var vehicle in vehiclesOnRoute) { if(vehicle is Car) { amountOfFuelToLoadOnTruck+=((Car)vehicle).AmountOfFuelNeededToFillTank(); } else if(vehicle is Airplane) { amountOfFuelToLoadOnTruck+=((Airplane)vehicle).AmountOfFuelNeededToFillLeftFuelTank(); amountOfFuelToLoadOnTruck+=((Airplane)vehicle).AmountOfFuelNeededToFillRightFuelTank(); } else if(vehicle is Boat) { amountOfFuelToLoadOnTruck+=((Boat)vehicle).AmountOfFuelNeededToFillFrontFuelTank(); amountOfFuelToLoadOnTruck+=((Boat)vehicle).AmountOfFuelNeededToFillRearFuelTank(); } } return amountOfFuelToLoadOnTruck; } }
使用动态性对这一方法进行重构,一避免用到交通工具类型的隐秘信息
public interface IFuelable { int GetTotalAmountOfFuelNeededForVehicle(); }
针对Vehicle类实现该接口
public class Car : Vehicle,IFuelable { public int GetTotalAmountOfFuelNeededForVehicle() { return AmountOfFuelNeededToFillTank(); } } public class Airplane : Vehicle,IFuelable { public int GetTotalAmountOfFuelNeededForVehicle() { return AmountOfFuelNeededToFillLeftFuelTank()+AmountOfFuelNeededToFillRightFuelTank(); } } public class Boat : Vehicle,IFuelable { public int GetTotalAmountOfFuelNeededForVehicle() { return AmountOfFuelNeededToFillFrontFuelTank()+AmountOfFuelNeededToFillRearFuelTank(); } }
重构结果:
public class FuelingStation { public int AddFuelToTruck(List<Vehicle> vehiclesOnRoute) { var amountOfFuelToLoadOnTruck=0; foreach(var vehicle in vehiclesOnRoute) { amountOfFuelToLoadOnTruck+=vehicle.GetTotalAmountOfFuelNeededForVehicle(); } return amountOfFuelToLoadOnTruck; } }
或者利用LINQ功能
public int AddFuelToTruck(List<Vehicle> vehiclesOnRoute) { return vehiclesOnRoute.Sum(vehicle=>vehicle.GetTotalAmountOfFuelNeededForVehicle()); }