根据实际情况来选择出行方式

周日外出去玩,出行方式有步行,骑行,公车。
每个人因人或环境等等因素而选择的方式有所不同。

简单工厂是符合此类型的。只有在运行时,才知道使用的哪种方法。

创建一个抽象类Base:

public abstract class Base
    {
        public abstract string Mode();
    }
Source Code


下面分别创建3个类别,Bus,ycling,Walk,它们需要重写抽象类的抽象方法。


public class Bus : Base
    {
        public override string Mode()
        {
            return this.GetType().Name;
        }
    }
Source Code




 public  class ycling : Base
    {

        public override string Mode()
        {
            return this.GetType().Name;
        }
    }
Source Code




public class Walk : Base
    {
        public override string Mode()
        {
            return this.GetType().Name;
        }
    }
Source Code

既然是简单工厂,在这个工厂类中,去根据条件来决定运行哪一个方法,此方法一般情况之下,使用static实现静态。

 public class Factory
    {
        public static Base Trip(int speed)
        {
            if (speed <= 7)
                return new Walk();
            if (speed > 7 && speed <= 20)
                return new ycling();
            if (speed > 20)
                return new Bus();

            return null;
        }
    }
Source Code


现在,我们可以在控制台中,运行上面写的工厂方法:


原文地址:https://www.cnblogs.com/insus/p/7986631.html