重构类以消除 switch case 的使用

19 浏览
0 Comments

重构类以消除 switch case 的使用

假设我有一个类,用于计算不同交通工具在不同距离上的旅行成本:

public class TransportationCostCalculator
{
    public double DistanceToDestination { get; set; }
    public decimal CostOfTravel(string transportMethod)
    {
        switch (transportMethod)
        {
            case "Bicycle":
                return (decimal)(DistanceToDestination * 1);
            case "Bus":
                return (decimal)(DistanceToDestination * 2);
            case "Car":
                return (decimal)(DistanceToDestination * 3);
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
}

这样做虽然可以,但是使用switch case语句可能会导致维护上的噩梦,而且如果我以后想要使用飞机或火车怎么办?那我就必须改变上面的类。有什么替代switch case语句的方法,以及对此有什么提示呢?

我想象在控制台应用程序中使用它,类似这样,可以通过命令行参数来运行,指定要使用的交通工具和您要旅行的距离:

class Program
{
    static void Main(string[] args)
    {
        if(args.Length < 2)
        {
            Console.WriteLine("Not enough arguments to run this program");
            Console.ReadLine();
        }
        else
        {
            var transportMethod = args[0];
            var distance = args[1];
            var calculator = new TransportCostCalculator { DistanceToDestination = double.Parse(distance) };
            var result = calculator.CostOfTravel(transportMethod);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

非常感谢任何提示!

0