C#中的服务定位器模式:怪异的代码?

时间:2017-01-16 07:55:58

标签: c# design-patterns

我决定在我的prj中使用服务定位器模式。但是我怀疑当前的代码是怪异的。问题是:我有3种类型,但第3种使用前2种,所以在我看来代码不行,我怎么能改进呢?

以下是代码:

public class ServiceLocator: IServiceLocator
{
    private static ServiceLocator _instance;

    private IDictionary<object, object> services;

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

        this.services.Add(typeof(IService1), new Service1());
        this.services.Add(typeof(IService2), new Service2());
        this.services.Add(typeof(IService3), new Service3(new Service1(), new Service2(), new Service4()));
    }

    public static ServiceLocator Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new ServiceLocator();
            }
            return _instance;
        }
    }

    public T GetService<T>()
    {
        return (T)services[typeof(T)];
    }
}

0 个答案:

没有答案