只有當您正在做的對象類型爲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