Static Provider Dictionary Design

痞子三分冷 提交于 2019-12-12 02:32:25

问题


I'm rethinking a current WCF service we're using right now. We do A LOT of loading XML to various databases. In some cases, we can store it as XML data, and in others, we need to store it as rowsets.

So I'm redesigning this service to accept different providers. My first thought, classic abstract factory, but now I'm having my doubts. Essentially, the service class has one operation contract method, Load. But to me, it seems silly to new-up provider instances every time Load is called.

Currently:

// 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);
    }
}

I'm thinking about changing to:

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);
    }
}

Is this a good approach? I like the idea of caching the providers, seems more efficient to me... though, I tend to overlook the obvious sometimes. Let me know your thoughts!


回答1:


Why can't you use both? Pass in your dependency into the Load method and if the type is already cached use the cached instance.

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);
}


来源:https://stackoverflow.com/questions/9399957/static-provider-dictionary-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!