[英]Extendable design pattern based on database records or enum values
我正在開發一個需要非常可擴展的項目。 它是基於字符串代碼或枚舉值執行操作。 我現在使用switch-case語句並手動調用方法。
我想要做的是遍歷數據庫記錄(並最終獲取枚舉值或字符串代碼),調用方法“PerformAction”並使以后可以實現類或方法。
public bool PerformAction(ActionToPerform actionToPerform)
{
bool isPerformed = false;
switch (actionToPerform.Action.Code)
{
case "MAIL":
isPerformed = Actions.SendEmail(actionToPerform);
break;
case "RESTART":
isPerformed = Actions.RestartSendport();
break;
case "EVENT-LOG":
isPerformed = Actions.AddToEventLog();
break;
}
//Do some more
return isPerformed;
}
我希望以后能夠實現SendEmail,RestartSendport和AddToEventLog等操作。 我知道這可以以某種方式使用反射並給方法命名CODE(例如“MAIL.cs”),這樣我就可以避免使用switch case並執行一次調用。
我需要這個非常動態,並且在另一個庫中,所以我想知道是否存在針對此類問題的最佳實踐或良好的設計模式。
您可以從創建字典開始:
private Dictionary<ActionType, ActionBase> actions;
因此,您可以執行以下操作,而不是switch (currentActionType)
:
if (actions.ContainsKey(currentActionType))
actions[currentActionType].Run(someArgs);
這樣,您可以將操作映射與操作調用分開。 映射可以在構造函數中完成:
actions[ActionType.SendEmail] = new SendEmailAction();
actions[ActionType.OtherAction] = new OtherAction();
在此之后,您可以將操作字典提取到單獨的ActionsRepository
並將其作為依賴項注入。 存儲庫可以有一個方法RegisterAction(ActionType type, ActionBase action)
用於在運行時創建映射。
如果您可以設法統一動作調用模式,則可以向基本Action類添加一些ID字段並以這種方式調用它:
public bool PerformAction(ActionToPerform actionToPerform)
{
bool isPerformed = false;
var foundAction = Actions.SingleOrDefault(a => a.Code == actionToPerform.Action.Code);
if (foundAction != null)
{
isPerformed = foundAction.Invoke();
}
//Do some more
return isPerformed;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.