2009-11-20 205 views
1

的字符串說你要解釋的一樣AABBCDEEFF命令參數的刺痛......和想法是每個字符代表,你必須採取對類的一些行動的命令時,醜陋的解決方案是寫一個大開關的情況下,但我不想用這個,任何人都可以建議一個更優雅的解決方案?解釋命令

+0

@all提示開關,目前我使用開關,但在我的情況有一個維護問題的命令列表我要支持可能會改變,或者說他們的行爲可能會改變 – redzedi

回答

0

對於C#,在更復雜的情況下的解決方案可以實現和接口,或添加屬性和使用反射來調用命令或方法。

OK,作爲一個例子,我創建了一些C#代碼

public class ExecuteSequence 
    { 
     Dictionary<string, Type> classes = new Dictionary<string, Type>(); 
     public void LoadClasses() 
     { 
      classes.Clear(); 
      //load all classes with attribute 
      //this can be done at startup once, or on requested refresh 
      foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) 
       foreach (Type type in assembly.GetTypes()) 
        foreach (object attribute in type.GetCustomAttributes(typeof(MethodAttribute), true)) 
         if (attribute.GetType() == typeof(MethodAttribute)) 
          classes.Add(((MethodAttribute)attribute).MethodName, type); 
     } 

     public string Execute(string sequence) 
     { 
      string retVal = ""; 
      foreach (char c in sequence) 
       if (classes.ContainsKey(c.ToString())) 
       { 
        IMethod method = (IMethod)Activator.CreateInstance(classes[c.ToString()]); 
        retVal += method.Execute(); 
       } 

      return retVal; 
     } 
    } 

    public class MethodAttribute : Attribute 
    { 
     private readonly string m_MethodName; 
     public MethodAttribute(string methodName) 
     { 
      m_MethodName = methodName; 
     } 
     public string MethodName 
     { 
      get { return m_MethodName; } 
     } 
    } 
    public interface IMethod 
    { 
     string Execute(); 
    } 

    [Method("A")] 
    public class MethodA : IMethod 
    { 
     public string Execute() 
     { 
      return "FOO"; 
     } 
    } 

    [Method("B")] 
    public class MethodB : IMethod 
    { 
     public string Execute() 
     { 
      return "BAR"; 
     } 
    } 

您可以限制掃描初始組件列表中,但如前所述,這應該只在啓動時加載。

希望這會有所幫助。

+0

實際上反映是一個糟糕的選擇,因爲它是一個資源怪物。我經常見到其他開發者濫用反思。 – Woot4Moo

+0

嗨,你能詳細解釋一下嗎?我正在考慮與Elalfer的迴應聯繫在一起,就像我們可以擁有一個帶有設施的命令對象的地圖來動態註冊它們,然後我的解釋模塊只需查找該地圖中的當前令牌並調用execute( )。不同於標準的命令模式,我的接收器將被固定,並且它必須由命令類中的上下文注入。因此,命令類的不同解釋實際上是同一接收器類上的調用的變體。您是否認爲我是以正確的方式? – redzedi

+0

我添加了一些更新來嘗試幫助解釋。 –

1

那麼我的建議是開關,因爲編譯器會優化它。有多少潛在角色會發生?

2

讓一切儘可能簡單。留在開關。

4

創建地圖等的方法:map<char, func_ptr>,然後用你的 「行動」 填補它:

act_map['A'] = &my_class::func_a 
.... 

for each c in str 
    arc_map[c]() 

真正的實現取決於你的語言。

但是,如果你有多達5-10行動比只使用開關。