2012-02-22 36 views
0

我正在反思我们现在使用的当前WCF服务。我们做了很多加载XML到各种数据库。在某些情况下,我们可以将其存储为XML数据,而在另一些情况下,我们需要将其存储为行集。静态提供程序字典设计

所以我重新设计这个服务来接受不同的提供者。我的第一个想法,经典的抽象工厂,但现在我有我的怀疑。本质上,服务类有一个操作合约方法Load。但对我来说,每次调用Load时,新的提供者实例似乎都很愚蠢。

目前:

// Obviously incomplete example: 
public class XmlLoaderService : IXmlLoaderService 
{ 
    readonly IXmlLoaderFactory _xmlLoaderFactory; 
    readonly IXmlLoader _xmlLoader; 

    public XmlLoaderService() 
    { 
     _xmlLoader = _xmlLoaderFactory(ProviderConfiguration configuration); 
    } 

    public void Load(Request request) 
    { 
     _xmlLoader.Load(request); 
    } 
} 

我在考虑更改为:

public class XmlLoaderService : IXmlLoaderService 
{ 
    static readonly IDictionary<int, IXmlLoader> _providerDictionary; 

    static public XmlLoaderService() 
    { 
     _providerDictionary = PopulateDictionaryFromConfig(); 
    } 

    public void Load(Request request) 
    { 
     // Request will always supply an int that identifies the 
     // request type, can be used as key in provider dictionary 

     var xmlLoader = _providerDictionary[request.RequestType]; 
     xmlLoader.Load(request); 
    } 
} 

这是一个好办法?我喜欢缓存提供商的想法,对我来说似乎更有效率......但是,我有时忽略这种显而易见的做法。让我知道你的想法!

回答

3

为什么你不能同时使用?将您的依赖关系传入Load方法,如果该类型已被缓存,请使用缓存实例。

public void Load(Request request) 
{ 
    // Request will always supply an int that identifies the 
    // request type, can be used as key in provider dictionary 

    IXmlLoader xmlLoader; 
    if(_providerDictionary.ContainsKey(request.RequestType)) 
    { 
     xmlLoader = _providerDictionary[request.RequestType]; 
    } 
    else 
    { 
     xmlLoader = //acquire from factory 
     _providerDictionary.Add(request.RequestType, xmlLoader); 
    } 
    xmlLoader.Load(request); 
} 
+0

谢谢,我假设您认为在这种情况下缓存提供者是一个可行的选择,所以我会接受为最好的(尽管是唯一的)答案!谢谢! – Didaxis 2012-02-22 19:08:34