如何重构代码,以避免[从访谈中出现多个if-s?

问题描述 投票:0回答:2

在采访中,我被问到以下问题:

我有以下方法:

public void foo(SomeObject o){
    if(o.matches(constant1)){
          doSomething1(); 
    }else if(o.matches(constant2)){
          doSomething2(); 
    }else if(o.matches(constant3)){
          doSomething3(); 
    }
    ....
}

问题是:you should refactor method above. What will you do?

在采访中,我不知道该怎么做。

现在我认为state设计模式适合此任务?

我对吗?您怎么看?

P.S。

我与同事进行了谈判。他认为strategy设计模式更合适。

P.S。

[另一位专家认为chain of responsibility设计模式更合适。

if-statement design-patterns refactoring strategy-pattern state-pattern
2个回答
0
投票

通常的答案是用命令替换条件

请参阅我为类似答案提供的其他答案:

Replacing if else statement with pattern


0
投票

在这种情况下,关键的重构工作是将行为变化分开并将其封装到对象中。这是应用策略模式的好用例。在您的情况下,您将拥有一个名为SomeObjectInterface的接口,该接口具有一个名为doS​​omething()的API。然后,您将获得接口的实现,每个实现都将根据执行策略进行实现。

public void foo(SomeObjectInterface o){ o.doSomething(); .... }

哪个doSomething()实现被调用将由对象o的实际类型确定。

您可以参考此帖子了解其背后的原理:http://blog.softwarerevisited.com/2015/06/strategy-pattern.html

© www.soinside.com 2019 - 2024. All rights reserved.