简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合。
1.在配置文件中配置类名以及相对应的DLL文件名称
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ApplePhone" value="DIP.ApplePhone,DIP"/>
<add key="Honor" value="DIP.Honor,DIP"/> </appSettings>
</configuration>
2.
抽象一个基础类:
public abstract class BasePhone
{
public int Id { get; set; }
public string Branch { get; set; }
public abstract void System();
public abstract void Call();
}
派生于基础类
public class ApplePhone : BasePhone
{
public override void System()
{
Console.WriteLine("IOS9.4");
}
public override void Call()
{
Console.WriteLine("Use {0} Call", this.GetType().Name);
}
}
public class Honor : BasePhone
{
//public int Id { get; set; }
//public string Branch { get; set; }
public override void System()
{
Console.WriteLine("Android6.0");
}
public override void Call()
{
Console.WriteLine("Use {0} Call", this.GetType().Name);
}
}
public class People
{
public int Id { get; set; }
public string Name { get; set; }
public void UsePhone(BasePhone phone)
{
Console.WriteLine("**********************************************");
Console.WriteLine("This is {0} 在使用 {1}", this.Name, phone.GetType().Name);
phone.System();
phone.Call();
}
}
/// <summary>
/// 1 细节与抽象:类与接口/抽象类
/// 2 依赖倒置原则(Dependence Inversion Principle)
/// 上端和下端之间,应该依赖于抽象,而不依赖于细节
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" 依赖倒置原则DIP");
People people = new People()
{
Id = 26,
Name = "Andy"
};
BasePhone phone = ObjectFactory.CreatePhoneReflection(PhoneType.ApplePhone);
people.UsePhone(phone);
Console.Read();
}
}
public class ObjectFactory
{
public static BasePhone CreatePhone(PhoneType phoneType)
{
BasePhone phone = null;
switch (phoneType)
{
case PhoneType.ApplePhone:
phone = new ApplePhone();
break;
case PhoneType.Mi:
phone = new Mi();
break;
case PhoneType.Honor:
phone = new Honor();
break;
default:
throw new Exception("wrong phoneType");
}
return phone;
}
//使用反射获取类库中的类名
public static BasePhone CreatePhoneReflection(PhoneType phoneType)
{
string classModule = ConfigurationManager.AppSettings[phoneType.ToString()];
Assembly assembly = Assembly.Load(classModule.Split(',')[1]);
Type type = assembly.GetType(classModule.Split(',')[0]);
object oPhone = Activator.CreateInstance(type);
return (BasePhone)oPhone;
}
}
public enum PhoneType
{
ApplePhone,
Honor
}