如何利用抽象工厂更换数据库

原创
2016-06-07 15:15:59 841浏览

VS中我们都加入了抽象工厂模式,都懂的这种模式可以用来更换数据库。具体应用起来大家都知道应用反射,首先我介绍下我的情况吧。 现在的情况是我的D层程序集和命名空间都为DAL,D层的类也都是以Sql为前缀来命名,例如SqlCancelCardDAL,在工厂中,我的代码时

VS中我们都加入了抽象工厂模式,都懂的这种模式可以用来更换数据库。具体应用起来大家都知道应用反射,首先我介绍下我的情况吧。

现在的情况是我的D层程序集和命名空间都为DAL,D层的类也都是以Sql为前缀来命名,例如SqlCancelCardDAL,在工厂中,我的代码时这么写的,大家可以看一下:

Imports DFactory
Imports IDAL
Imports System.Reflection
Imports System.Configuration

Public Class DataAccess   
    Private ReadOnly assemblyName As String = "DAL"
    Dim strDB As String = System.Configuration.ConfigurationSettings.AppSettings("DB")

    '返回一个IStudent接口
    Public Function CheckStuID() As IStudent
        Dim ClassName As String = assemblyName + "." + strDB + "StuInfoDAL"
        Return CType(Assembly.Load("DAL").CreateInstance(ClassName), IStudent)
    End Function

    '返回注册接口IRegist
    Public Function AboutRegist() As IRegist
        Dim ClassName As String = assemblyName + "." + strDB + "RegistDAL"
        Return CType(Assembly.Load("DAL").CreateInstance(ClassName), IRegist)
    End Function

    '返回充值接口ICharge
    Public Function InsertInfo() As ICharge
        Dim ClassName As String = assemblyName + "." + strDB + "ChargeDAL"
        Return CType(Assembly.Load("DAL").CreateInstance(ClassName), ICharge)
    End Function
   ......
  End Class

App.config中反射为:


改变为

接着想,我们原来的命名空间跟改变的OracleDAO命名空间完全不一样,看一下原来的工厂代码这样写的:

 Private ReadOnly assemblyName As String = "DAL"

这样就在程序里把命名空间给写死了,但是我们同样可以利用反射的原理将命名空间移动到XML中,不需要打开VS来看,因为我们的运行都是从项目文件中UI层Debug开始的,所以只需在UI\bin\Debug\UI.exe.config中添加一句:


同时在工厂层中将写死的命名空间那句改为:

 Private ReadOnly assemblyName = System.Configuration.ConfigurationSettings.AppSettings("MM")

最后一步就是:将每个方法中的return句中“DAL”改为assemblyName即为完美。

这样我们的程序如何更改数据库只需在配置文件中更改命名空间和反射中类的前缀即可,这样就充分运用了抽象工厂+反射,实现更换数据库的功能。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。