我决定在我的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)];
}
}