只有当您正在做的对象类型为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.
请提供一些更多的代码,如果你正在寻找一个多态性教程,你可能会发现它在网络上的任何地方。请举一些例子。 – amirouche 2011-02-01 19:18:50
无法在此处添加所有代码。我在下面提供了一个示例(查找Charles) – Charles 2011-02-01 20:09:11
您可以使用反射api替换剩余的条件。根据字符串在运行时确定要实例化的基本动作的类型。有一个倒下来,你的字符串应该与你的基本动作的确切名称相匹配。您还可以使用哈希映射将基本操作映射到字符串,并在运行时进行选择。 – 2016-03-21 05:14:15