用多态替换条件-理论上不错,但不实用 [英] Replace conditional with polymorphism - nice in theory but not practical
问题描述
仅当您正在为其选择switch/if语句的对象类型已经为您选择时,用多态替换条件"才是优雅的.例如,我有一个Web应用程序,该应用程序读取一个称为"action"的查询字符串参数.动作可以具有视图",编辑",排序"等值.那么我该如何通过多态实现呢?好吧,我可以创建一个名为BaseAction的抽象类,并从中派生ViewAction,EditAction和SortAction.但是我不需要条件来确定要实例化哪种类型的BaseAction吗?我看不到如何用多态性完全替换条件语句.如果有的话,条件条件只会被推到链的顶端.
"Replace conditional with polymorphism" is elegant only when type of object you're doing switch/if statement for is already selected for you. As an example, I have a web application which reads a query string parameter called "action". Action can have "view", "edit", "sort", and etc. values. So how do I implement this with polymorphism? Well, I can create an abstract class called BaseAction, and derive ViewAction, EditAction, and SortAction from it. But don't I need a conditional to decided which flavor of type BaseAction to instantiate? I don't see how you can entirely replace conditionals with polymorphism. If anything, the conditionals are just getting pushed up to the top of the chain.
public abstract class BaseAction
{
public abstract void doSomething();
}
public class ViewAction : BaseAction
{
public override void doSomething() { // perform a view action here... }
}
public class EditAction : BaseAction
{
public override void doSomething() { // perform an edit action here... }
}
public class SortAction : BaseAction
{
public override void doSomething() { // perform a sort action here... }
}
string action = "view"; // suppose user can pass either "view", "edit", or "sort" strings to you.
BaseAction theAction = null;
switch (action)
{
case "view":
theAction = new ViewAction();
break;
case "edit":
theAction = new EditAction();
break;
case "sort":
theAction = new SortAction();
break;
}
theAction.doSomething(); // So I don't need conditionals here, but I still need it to decide which BaseAction type to instantiate first. There's no way to completely get rid of the conditionals.
推荐答案
您是对的-条件被推到了链的顶端" –但是,这并不是正当的".它非常强大.正如@thkala所说,您只需选择一次即可;从此开始,对象便知道如何开展业务.您描述的方法-BaseAction,ViewAction和其他方法-是实现它的好方法.尝试一下,看看您的代码变得更干净了.
You're right - "the conditionals are getting pushed up to the top of the chain" - but there's no "just" about it. It's very powerful. As @thkala says, you just make the choice once; from there on out, the object knows how to go about its business. The approach you describe - BaseAction, ViewAction, and the rest - is a good way to go about it. Try it out and see how much cleaner your code becomes.
当您有一个使用诸如"View"之类的字符串并返回一个Action的工厂方法,并调用该方法时,您已经隔离了条件.那太棒了.在尝试之前,您将无法正确欣赏它的强大功能-因此请试一试!
When you've got one factory method that takes a string like "View" and returns an Action, and you call that, you have isolated your conditionality. That's great. And you can't properly appreciate the power 'til you've tried it - so give it a shot!
这篇关于用多态替换条件-理论上不错,但不实用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!