多态如何替换循环内的if-else语句?

Wol*_*gon 17 language-agnostic oop polymorphism loops if-statement

多态如何在循环中替换if-else语句或Switch?特别是它总能取代if-else?我在循环中使用的大多数if-thens都是算术比较.这个问题是从这个问题中产生的.

int x;
int y;
int z;

while (x > y)
{
     if (x < z)
     {
         x = z;
     }
}
Run Code Online (Sandbox Code Playgroud)

如何使用多态?
注意:我用Java编写了这个,但我对任何OOL感兴趣.

Jon*_*eet 25

当每个案例对应不同类型时,多态通常会替换switch语句.所以不要:

public class Operator
{
    string operation;

    public int Execute(int x, int y)
    {
         switch(operation)
         {
             case "Add":
                 return x + y;
             case "Subtract":
                 return x - y;
             case "Multiply":
                 return x * y;
             case "Divide":
                 return x / y;
             default:
                 throw new InvalidOperationException("Unsupported operation");
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

你有:

public abstract class Operator
{
    public abstract int Execute(int x, int y);
}

public class Add : Operator
{
    public override int Execute(int x, int y)
    {
        return x + y;
    }
}

// etc
Run Code Online (Sandbox Code Playgroud)

但是,对于您提供的比较类型的决策,多态性确实无济于事.