关于IOC
Ioc英文为 Inversion of Control,即反转模式。它的主要目的是解耦,即解决调用者和被调用者之间的强耦合问题。
举个例子:
2{
3 private ILog _Logger;
4 public ILog Logger {
5 get { return _Logger;}
6 set { _Logger=value; }
7 }
8 public void DoSomething(){
9 Logger.WriterLog("log");
10 }
11 public static void Main()
12 {
13 Business B=new Business();
14 ILog logger=new Log();
15 B.Logger=logger;
16 B.DoSomething();
17 }
18}
19
20public interface ILog{
21 void WriterLog(string s);
22}
23public class Log : ILog
24{
25 public void WriterLog(string s){
26 Console.WriteLine(s);
27 }
28}
29
在以上的代码中,可以看出Business与ILog是紧耦合的,在调用Business类的对象时,需要实例化一个ILog的具体类(见14、15行)。其类图见图1。
使用IOC(采用Spring.net实现)就比较简单,其调用例子如下:
{
IApplicationContext ctx
= ConfigurationSettings.GetConfig( "spring/context") as IApplicationContext;
Business B = (Business) ctx.GetObject("Business");
B.DoSomething();
Console.ReadLine();
}
此外,还需要在Config文件中进行配置,配置如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net" >
<description></description>
<object name="Business" type="IOCExample.Business, IOCExample">
<property name="Logger">
<ref object="AnLog" />
</property>
</object>
<object name="AnLog" type="IOCExample.Log, IOCExample"> </object>
</objects>
</spring>
</configuration>
关键在于objects 结点的定义,其中定义了类与类之间的依赖关系。 通过这个例子可以看出,使用IOC的意义在于将两个类之间的关联放到了配置文件之中(而并非删除这种关联),其类图如图2.