2013-03-25 48 views
2

考慮以下如何編寫一個服務定位器模式,其中的具體類實現相同的接口/服務?

class ServiceA : IServiceA 
    { 
     public void SayHelloFromA() 
     { 
      Console.WriteLine("Hello Service A"); 
      Console.ReadKey(); 
     } 
    }  
    class ServiceB : IServiceB{ } 
    class ServiceC : IServiceC{ } 
    interface IServiceA 
    { 
     void SayHelloFromA(); 
    } 
    interface IServiceB{ } 
    interface IServiceC{ } 

如果我想使用Service Locator模式,提供here作品完美的例子。

現在說另一個類實現IServiceA接口,如下所示。

class ServiceA1 : IServiceA 
{ 
    public void SayHelloFromA() 
    { 
     Console.WriteLine("Hello Service A1"); 
     Console.ReadKey(); 
    } 
} 

並相應地,我需要的服務爲下

internal ServiceLocator()  
     {   
      services = new Dictionary<object, object>();   

      this.services.Add(typeof(IServiceA), new ServiceA()); 
      this.services.Add(typeof(IServiceA), new ServiceA1());  
      this.services.Add(typeof(IServiceB), new ServiceB());   
      this.services.Add(typeof(IServiceC), new ServiceC());  
     } 

添加到字典,這是錯誤的,因爲重複鍵不能出現在字典中。

那麼我該如何解決這個問題呢?應該如何改變數據結構,以便服務定位器可以兼容這兩者。

NB〜我想實現我廠的Srvice Locator模式方法

public class CustomerFactory : ICustomerBaseFactory 

{ 

      public IBaseCustomer GetCustomer(string CustomerType) 

      { 
        switch(CustomerType) 

        { 
          case "1": return new Grade1Customer(); break; 

          case "2": return new Grade2Customer(); break; 

          default:return null; 
        } 
      } 
} 

在具體工廠從獲得IBaseCustomer

感謝

+1

你將如何檢索特定的實現?服務定位器的全部重點是給你一個IServiceA的實現,而不知道它是哪一個。在你的例子中,你將如何調用服務定位器來獲得特定的實現? (假設你可以有一個帶有重複項的鍵控容器) – Seb 2013-03-25 10:09:19

回答

0

你有沒有考慮一個字典每個抽象類型由嵌套在頂級字典中的具體類型所鍵入?

Dictionary<T, Dictionary<T, U>> 

這樣,您可以按類型查詢頂級字典,然後查詢實現該類型的所有服務的子字典。

例如

var services = new Dictionary<Type, Dictionary<Type, Object>>(); 

現在,你可以要求服務字典類型:

services.TryGetValue(typeof(IServiceA), componentDictionary); 

如果返回true,那麼你知道componentDictionary將包含實現該服務的組件:

foreach (c in componentDictionary.Values) {... } 

通過巧妙地使用抽象基類型和泛型,您可以創建比這更強大的類型化解決方案。然而,這應該工作得很好,雖然鑄造。

+0

你可以舉個例子嗎? – 2013-03-25 10:11:29

+0

我已經更新了答案,以進一步展示這個概念。基本上,您的服務定位器需要一個標識映射來保存/解析組件到服務。 – 2013-03-25 10:28:11

0

在Java中,有一個支持每個鍵多個值的類。我相信你可以爲C#找到一個類似的數據結構。

相關問題