项目结构如下:
SimpleFactory类:
namespace Factory { public class SimpleFactory { private static string IPeoPleAssambly = ConfigurationManager.AppSettings["IPeoPleAssambly"]; private static string IMobileAssambly = ConfigurationManager.AppSettings["IMobileAssambly"]; //配置文件+映射 ----> 创建对象 public static IPeoPle CreateIPeoPle() { //加载指定的托管程序集(类库)到当前应用程序域中 Assembly assembly = Assembly.Load(IPeoPleAssambly.Split(',')[1]); //获取程序集中具有指定名称的Tyle对象 Type type = assembly.GetType(IPeoPleAssambly.Split(',')[0]); //创建对象,并返回 return (IPeoPle)Activator.CreateInstance(type); } //配置文件+映射 ----> 创建对象 public static IMobile CreateIMobile() { //加载托管程序集到当前应用程序域中 Assembly assembly = Assembly.Load(IMobileAssambly.Split(',')[1]); //获取程序集中具有指定名称的Tyle对象 Type type = assembly.GetType(IMobileAssambly.Split(',')[0]); //创建对象,并返回 return (IMobile)Activator.CreateInstance(type); } } }
IPeoPle接口:
namespace PeoPle { public interface IPeoPle { void Play(IMobile mobile); } }
Student类:
namespace PeoPle { public interface IPeoPle { void Play(IMobile mobile); } }
IMobile接口:
namespace Mobile { public interface IMobile { void Play(); } }
IPhone类:
namespace Mobile { class IPhone : IMobile { public void Play() { Console.WriteLine("我在玩IPhone"); } } }
VIVO类
namespace Mobile { class IPhone : IMobile { public void Play() { Console.WriteLine("我在玩IPhone"); } } }
配置文件:
<appSettings> <add key="IPeoPleAssambly" value="PeoPle.Student,PeoPle" /> <add key="IMobileAssambly" value="Mobile.IPhone,Mobile" /> </appSettings>
目前我们的需求是:
依赖倒置原则:面向抽象,而不是面向细节
难题:既不想依赖细节,又想创建对象怎么办?
解决:把创建对象的事交给第三方来做
实现如下:
1.工厂模式(配置文件+映射---->创建对象)
namespace IOC { public class Test1 { public Test1() { IPeoPle people = SimpleFactory.CreateIPeoPle(); IMobile mobile = SimpleFactory.CreateIMobile(); people.Play(mobile); } } }
输出:我在玩iphone
1)现在突然我不想玩iphone了,我想玩vivo,那么我们只需要改配置文件就可以了
配置文件修改如下(把key 为 IMobileAssambly 更改为 Mobile.VIVO,Mobile):
<appSettings> <add key="IPeoPleAssambly" value="PeoPle.Student,PeoPle" /> <add key="IMobileAssambly" value="Mobile.VIVO,Mobile" /> </appSettings>
输出:我在玩VIVO
2.IOC控制反转