实现高层依赖低层通过抽象类来实现,保证项目的可扩展性
作者:互联网
//让系统完全遵照依赖倒置原则来实现
//当需要一个对象又不想直接New,用工厂来实现
//在工厂中想要即不依赖细节,又能创建对象,使用反射+配置文件+工厂
//将项目配置在配置文件中的实现类的DLL,放到项目的bin文件中,这样项目编译的时候,不会引用
//使用依赖倒置原则
//1.可配置,需要使用不同的手机只需要修改配置文件
//2.可扩展,添加新的手机模型之后,最后需要将DAL的DLL添加到项目的bin目录下,修改配置文件就可以了,不需要修改其他的代码
//3.支持版本的升级替换,只需要将新升级的类库或者服务的DLL添加到项目的bin目录下,修改配置文件就可以了
IStudentService studentService = SimpleFactory.CreateStudentService();
studentService.Study();
AbstractPhone phone = SimpleFactory.CreatePhone();
studentService.Play(phone);
public interface IStudentService
{
void Study();
void Play(AbstractPhone phone);
}
namespace IDAL
{
public abstract class AbstractPhone
{
public int Id { get; set; }
public string Name { get; set; }
public abstract void System();
public abstract void Phone();
public abstract void Text();
}
}
public class StudentService : IStudentService
{
public void Study()
{
Console.WriteLine("Student study");
}
public void Play(AbstractPhone phone)
{
Console.WriteLine("Play: " + phone.Name);
}
}
namespace Factory
{
public class SimpleFactory
{
/// <summary>
/// 配置文件+反射+工厂-->IOC容器雏形
/// </summary>
private static string IStudentServiceAssembly = ConfigurationManager.AppSettings["IStudentServiceAssembly"];
private static string IAbstractPhoneAssembly = ConfigurationManager.AppSettings["AbstractPhone"];
public static IStudentService CreateStudentService()
{
IStudentService studentService = null;
try
{
Assembly assembly = Assembly.Load(IStudentServiceAssembly.Split(',')[1]);//加载一个dll
Type type = assembly.GetType(IStudentServiceAssembly.Split(',')[0]);//传入类名获取类型
studentService = (IStudentService)Activator.CreateInstance(type);
}
catch(Exception ex)
{
}
return studentService;
}
public static AbstractPhone CreatePhone()
{
AbstractPhone phone = null;
try
{
Assembly assembly = Assembly.Load(IAbstractPhoneAssembly.Split(',')[1]);//加载一个dll
Type type = assembly.GetType(IAbstractPhoneAssembly.Split(',')[0]);//传入类名获取类型
phone = (AbstractPhone)Activator.CreateInstance(type);
}
catch (Exception ex)
{
}
return phone;
}
}
}
<appSettings>
<add key="IStudentServiceAssembly" value="BLL.StudentService,BLL"/>
<add key="AbstractPhone" value="DAL.IPhone,DAL"/>
</appSettings>
namespace BLL
{
public class StudentService : IStudentService
{
public void Study()
{
Console.WriteLine("Student study");
}
public void Play(AbstractPhone phone)
{
Console.WriteLine("Play: " + phone.Name);
}
}
}
标签:配置文件,可扩展性,void,public,phone,IStudentService,抽象类,低层,AbstractPhone 来源: https://www.cnblogs.com/fblogs/p/12150398.html