继承如何取代交换机案例?

Jit*_*dav 2 c#

我使用C#Switch案例如何使用继承替换.case就像1,2,3,4所以我可以如何实现它.

例如:

    public Blocks(int code)
    {
         bool[,] shp1;

        switch (code)
        {
            case 1:
                this._Width = 4;
                this._Height = 1;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[1, 0] = true;
                shp1[2, 0] = true;
                shp1[3, 0] = true;
                this.Shape = shp1;
                break;

            case 2:
                this._Width = 2;
                this._Height = 2;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[0, 1] = true;
                shp1[1, 0] = true;
                shp1[1, 1] = true;
                this.Shape = shp1;
                break;


            default:
                throw new ArgumentException("Invalid Block Code");
        }
    }
Run Code Online (Sandbox Code Playgroud)

tva*_*son 9

基本思想是,不是有一个基于状态决定做什么的方法,而是有不同类型的对象,它们具有相同方法的不同实现,为该类型的对象做正确的事情.

假设您现在有一个Car类,值(1,2,3,...)指的是各种制动配置.在您当前的Brake()方法中,您的代码如下所示:

public class Car
{
    public void Brake()
    {
          switch (this.BrakeType)
          {
              case 1:  // antilock brakes
                ....
              case 2:  // 4-wheel disc brakes, no antilock
                ....
              case 3:  // rear-drum, front-disc brakes
                ....

          }
     }
}
Run Code Online (Sandbox Code Playgroud)

你真正想要做的是有不同的类来实现Brake方法.在这种情况下,我会为每种制动类型配备BrakeStrategy.为汽车对象配置正确的BrakeStrategy,然后只需从Brake方法调用策略方法.

public class Car
{
     public BrakeStrategy BrakeStrategy { get; set; }

     public void Brake()
     {
         this.BrakeStrategy.Brake();
     }
}

public class ABSBrakes : BrakeStrategy
{
     public void Brake()
     {
        ... do antilock braking...
     }
}

var car = new Car { BrakeStrategy = new ABSBrakes(), ... };
car.Brake();  // does ABS braking
Run Code Online (Sandbox Code Playgroud)

  • 您必须确实有某种决策结构来创建您想要使用的制动策略.这可以转移到你确实使用switch语句的工厂模式,但是,这个语句远比原始语句复杂.接下来,在需要时引入新的制动策略要容易得多. (2认同)
  • @Preets - @Frederik是正确的 - 你需要一些方法来确定要创建什么类型的东西.这可以通过配置工厂 - 工厂读取配置来完成,配置指定要创建的策略的类型(按名称).即使您最终使用决策树 - 这可以放入专用于对象的创建方面的类中,而不是在整个类中传播操作逻辑.也就是说,switch语句本地化在创建对象的位置,而不是在每个方法中使用以确定如何操作此对象. (2认同)