c# 解耦合

来源:互联网 发布:测试环境执行sql指令 编辑:程序博客网 时间:2024/05/16 09:06

工厂:顾名思义即为可以以加工的形式生成类的对象。需要工厂类、加工方法、产品的模型。

工厂的作用在于解决耦合。

耦合的不良影响:通俗的讲 

模块一的实现依赖于模块二,更改模块二后,模块一也得更改,那么二者就有耦合。
大型的程序必然不能出现这种情况,以本人相当匮乏的经验来看,耦合的类设计降低了代码的维护性。
//接口:接口是一种契约
    public interface IShowMsg    {        void showMsg();    }
    public class SomeProperty : IShowMsg    {        public string Size { get; set; }        public string Type { get; set; }        public void showMsg()        {            Console.WriteLine("会变的方法");        }    }
//工厂类
    public static class Coupling     {        public static IShowMsg CreateObject()        {            return new SomeProperty();        }    }

//spring 控制反转配置文件 IOC
<?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 id="SomeProperty" type="FactoryTest.SomeProperty, FactoryTest" />    </objects>  </spring></configuration>
 class Program    {        static void Main(string[] args)        {                        //体现耦合            IShowMsg ds=new SomeProperty();            ds.showMsg();            Console.WriteLine("耦合");            //部分解耦合 工厂模式            IShowMsg ds1=Coupling.CreateObject();            ds1.showMsg();            Console.WriteLine("部分解耦和");    
//spring             IApplicationContext ctx = ContextRegistry.GetContext();            IShowMsg ds2 = ctx.GetObject("SomeProperty") as IShowMsg;            if (ds2 != null)            {                ds2.showMsg();                }            Console.WriteLine(".net spring 解耦和");                        Console.ReadKey();        }    }

0 0