Service Locator 服务定位模式

时间:2023-03-08 17:47:26
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ServiceLocator
{
class Program
{
static void Main(string[] args)
{
var conObj = (IConsoleIml)ServiceLocator.Loctory.GetServiceByType(typeof(IConsoleIml));
conObj.Console("");
Console.Read();
}
} public sealed class ServiceLocator
{
private static readonly ServiceLocator locator = new ServiceLocator();
private static readonly InitialContext initialContext = new InitialContext();
public object GetServiceByType(Type serviceType)
{
return initialContext.GetService(serviceType);
}
public static ServiceLocator Loctory { get { return locator; } }
}
public class InitialContext
{
public Dictionary<Type, ServiceFactoryBase> dic = new Dictionary<Type, ServiceFactoryBase>();
public InitialContext()
{
foreach (var item in this.GetType().Assembly.GetExportedTypes())
{
if (item.IsSubclassOf(typeof(ServiceFactoryBase)))
{
var factory = (ServiceFactoryBase)Activator.CreateInstance(item);
dic.Add(factory.ServiceType, factory);
}
}
} public object GetService(Type ServiceType)
{
var serviceFactory = dic[ServiceType];
if (serviceFactory != null)
return serviceFactory.GetService();
throw new InvalidOperationException();
}
}
public abstract class ServiceFactoryBase
{
private object serviceIml = null;
public object GetService()
{
if (serviceIml == null)
{
serviceIml = this.DoGetservice();
}
return serviceIml;
}
protected abstract object DoGetservice();
public abstract Type ServiceType { get; }
}
public class ConsoleFactory : ServiceFactoryBase
{
protected override object DoGetservice()
{
return new ConsoleIml();
} public override Type ServiceType
{
get { return typeof(IConsoleIml); }
}
}
public interface IConsoleIml
{
void Console(string content);
}
public class ConsoleIml : IConsoleIml
{
public void Console(string content)
{
System.Console.WriteLine(content);
}
} }