refactoring - 用多态替换条件 - 理论上很好但不实用

标签 refactoring polymorphism conditional

“用多态替换条件”只有在已经为您选择了您正在执行 switch/if 语句的对象类型时才优雅。例如,我有一个 Web 应用程序,它读取一个名为“action”的查询字符串参数。操作可以具有“查看”、“编辑”、“排序”等值。那么我如何用多态来实现它呢?好吧,我可以创建一个名为 BaseAction 的抽象类,并从中派生出 ViewAction、EditAction 和 SortAction。但是我不需要一个条件来决定要实例化哪种类型的 BaseAction 吗?我不明白如何用多态完全替换条件。如果有的话,条件只是被推到链的顶部。

编辑:

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 和其他方法 - 是一个很好的方法。试试看,看看你的代码变得多么干净。

当你有一个工厂方法接受一个像 "View"这样的字符串并返回一个 Action 并且你调用它时,你已经隔离了你的条件。那太棒了。除非您尝试过,否则您无法正确地欣赏这种力量——所以试一试吧!

关于refactoring - 用多态替换条件 - 理论上很好但不实用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4866873/

相关文章:

组合目录和文件路径 - C

c# - 从父类ctor调用重写的方法

clojure - 在重复时停止和拆分生成的序列 - clojure

没有 else 的 Ruby 三元运算符

c# - Java 增强的 for 循环 VS .NET foreach 循环

c# - 项目引用条件包含多个条件

reflection - 如何优化此方法

css - 我如何重构CSS?

c# - 关于C#自动实现属性的问题

java - 如何调用类层次结构中的方法?