Service Locator 服务定位模式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ServiceLocator
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             var conObj = (IConsoleIml)ServiceLocator.Loctory.GetServiceByType(typeof(IConsoleIml));
14             conObj.Console("123");
15             Console.Read();
16         }
17     }
18 
19     public sealed class ServiceLocator
20     {
21         private static readonly ServiceLocator locator = new ServiceLocator();
22         private static readonly InitialContext initialContext = new InitialContext();
23         public object GetServiceByType(Type serviceType)
24         {
25             return initialContext.GetService(serviceType);
26         }
27         public static ServiceLocator Loctory { get { return locator; } }
28     }
29     public class InitialContext
30     {
31         public Dictionary<Type, ServiceFactoryBase> dic = new Dictionary<Type, ServiceFactoryBase>();
32         public InitialContext()
33         {
34             foreach (var item in this.GetType().Assembly.GetExportedTypes())
35             {
36                 if (item.IsSubclassOf(typeof(ServiceFactoryBase)))
37                 {
38                     var factory = (ServiceFactoryBase)Activator.CreateInstance(item);
39                     dic.Add(factory.ServiceType, factory);
40                 }
41             }
42         }
43 
44         public object GetService(Type ServiceType)
45         {
46             var serviceFactory = dic[ServiceType];
47             if (serviceFactory != null)
48                 return serviceFactory.GetService();
49             throw new InvalidOperationException();
50         }
51     }
52     public abstract class ServiceFactoryBase
53     {
54         private object serviceIml = null;
55         public object GetService()
56         {
57             if (serviceIml == null)
58             {
59                 serviceIml = this.DoGetservice();
60             }
61             return serviceIml;
62         }
63         protected abstract object DoGetservice();
64         public abstract Type ServiceType { get; }
65     }
66     public class ConsoleFactory : ServiceFactoryBase
67     {
68         protected override object DoGetservice()
69         {
70             return new ConsoleIml();
71         }
72 
73         public override Type ServiceType
74         {
75             get { return typeof(IConsoleIml); }
76         }
77     }
78     public interface IConsoleIml
79     {
80         void Console(string content);
81     }
82     public class ConsoleIml : IConsoleIml
83     {
84         public void Console(string content)
85         {
86             System.Console.WriteLine(content);
87         }
88     }
89 
90 }

 

posted @ 2014-02-09 19:53  zqcoder  阅读(1252)  评论(0编辑  收藏  举报