使用访问者模式来处理else if [英] Use visitor pattern to handle else if
问题描述
我想知道是否有任何方式处理访问者模式的简单条件?
I wonder if there is any way to handle a simple condition with the visitor pattern or not?
例如,如果我们有以下代码,我们如何应用访问者模式?
For instance, if we have the below code, how can we apply the visitor pattern to it?
public class Elseif
{
private int total;
public int Condition(int x)
{
if(x==1)
{
total = 100;
}
else if(x==2)
{
total = 200;
}
return total;
}
}
换句话说,你想要写入IVisitor界面的重载?
in other words how you want to write the overload for IVisitor interface ?
public interface IVisitor
{
int Visitor(int x);
}
推荐答案
访客模式用于区分不同的类型,特别是如果您有一个(抽象)超类的对象,并且您想要根据具体的类型执行特殊操作。这意味着,您可以(而且应该)使用它,而不是使用if-then-else来进行转换测试。
The Visitor Pattern is for distinguishing different types, espacially if you have an object of an (abstract) superclass, and you want to do special things depending on the concrete type. That means, you can (and should) use it instead of an if-then-else with casting-tests.
访问者模式不用于区分值。
The Visitor Pattern is not for distinguishing values.
这篇关于使用访问者模式来处理else if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!