2016-05-12 48 views
-1

請考慮下面的代碼。我想根據bindingtype創建一個service。我已經爲它創建了一個switch的案例,但是我對這個方法並不滿意,我想避免switch聲明爲將來可擴展性。請建議一個更好的模式或設計來做到這一點。避免在編碼中使用Switch語句的模式和編碼風格

public static object CreateBinding(string binding, object service) 
    { 
     switch (binding) 
     { 
      case "ServiceA": 
       ChannelFactory<IServiceA> ServiceFactoryA = new ChannelFactory<IServiceA> (binding); 
       service = ServiceFactoryA.CreateChannel(); 
       break; 

      case "ServiceB": 
       ChannelFactory<IServiceB> ServiceFactoryB = new ChannelFactory<IServiceB> (binding); 
       service = ServiceFactoryB.CreateChannel(); 
       break; 

      default: 
       ChannelFactory<IServiceC> ServiceFactoryC = new ChannelFactory<IServiceC> (binding); 
       service = ServiceFactoryC.CreateChannel(); 
       break; 
     } 

     OpenChannel(service); 

     return service; 
    } 
+0

有許多關於重構'switch'語句的問題/文章。展示你已經嘗試過的東西是個好主意。事實上,爲您的案例獲得量身定製的代碼是很好的,但這不是真正的目標。 –

+0

這是一個有據可查的重構模式的常見問題:http://refactoring.com/catalog/replaceConditionalWithPolymorphism.html –

回答

4

對我來說,最明顯的方法來刪除switch語句是使用Dictionary

方法如下:

private static Dictionary<string, Func<string, object>> _bindingFactory = new Dictionary<string, Func<string, object>>() 
{ 
    { "ServiceA", binding => new ChannelFactory<IServiceA>(binding).CreateChannel() }, 
    { "ServiceB", binding => new ChannelFactory<IServiceB>(binding).CreateChannel() }, 
    { "", binding => new ChannelFactory<IServiceC>(binding).CreateChannel() }, 
}; 

public static object CreateBinding(string binding, object service) 
{ 
    service = _bindingFactory[_bindingFactory.ContainsKey(binding) ? binding : ""](binding); 
    OpenChannel(service); 
    return service; 
} 

這是有點奇怪,你有object service作爲參數傳遞給CreateBinding,但我把它原樣。

現在完全有可能在運行時更改_bindingFactory以產生任何類型的可擴展性。