从网上查找资料的时候发现很多同学都写过这篇博客了,可见我的方向没有跑偏。虽然我们学设计模式的时候已经接触过抽象工厂模式,大话设计模式中每个设计模式都紧密联系生活,而且主人公讲的也相当有趣,但是真正运用起来却没那么简单。可以说小菜只是帮我们理解了各个设计模式的用途以及有确定,真正的理解还需要我们自己动手实践。
主要就是为了提高软件的灵活性,运用抽象工厂+反射+配置文件可以很方便的更换数据库。引入接口之后,就可以对外提供一致的接口,而我们既可以用SQLServer实现接口,也可以用AccessDAL实现,能够更好地为B层和D层解耦合。
我们就以机房收费系统用户登录为例,讲解如何具体运用:
这里我们用的是SQLServer数据库,配置文件如下:
<span style="font-family:KaiTi_GB2312;font-size:18px;"> <appSettings> <add key ="DB" value="Sqlserver"/> <add key="ConnStr" value="server=.;database=JFSF_Recharge;User ID=sa;Password=123456"/> </appSettings></span>U层负责接收和输出数据信息,通过B层的返回值显示用户是否登陆成功。
<span style="font-family:KaiTi_GB2312;font-size:18px;"> Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click If IsEmptyText(Me) = True Then '调用遍历函数判断文本框和选择框是否为空 Exit Sub Else Dim thisUser As Entity.LoginModel = New Entity.LoginModel '定义一个实体对象来获得文本框的内容 thisUser.user_name = txtUserid.Text.Trim() thisUser.user_pwd = txtPassword.Text Dim ub As BLL.Loginbll = New BLL.Loginbll '定义一个B层对象,通过B层返回结果,通知用户信息 If ub.IsUser(thisUser) Then MessageBox.Show("登陆成功,欢迎使用!") Me.Hide() frmmain.Show() Else MessageBox.Show("登录失败,请重新输入!") Call NotEmptyText(Me) End If End If End Sub</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"> Public Function IsUser(ByVal user As Entity.LoginModel) As Boolean Dim factory As New Factory.DBFactory '定义一个接口变量 Dim IUser As IUserInfo '调用查找用户的工厂方法 IUser = factory.FindUser Dim table As DataTable Dim flag As Boolean table = IUser.QueryUserInfo(user) If table.Rows.Count = 0 Then flag = False Else flag = True End If Return flag End Function</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"> Private Shared ReadOnly AssemblyName As String = "DAL" '声明程序集的名称 Private Shared ReadOnly db As String = ConfigurationManager.AppSettings("DB") '读取配置文件 Public Function FindUser() As IDAL.IUserInfo Dim className As String = AssemblyName + "." + db + "LoginDAL" '定义类名初值为DAL.SqlserverLoginDAL Dim iuser As IUserInfo iuser = CType(Assembly.Load(AssemblyName).CreateInstance(className), IUserInfo) '使用反射 Return iuser End Function</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">Public Interface IUserInfo '查询用户的接口函数 Function QueryUserInfo(ByVal user As Entity.LoginModel) As DataTable End Interface</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">Public Class SqlserverLoginDAL : Implements IUserInfo '实现接口函数 '重写接口中查找用户方法 Function QueryUserInfo(ByVal user As Entity.LoginModel) As DataTable Implements IUserInfo.QueryUserInfo Dim strSQL As String = "select * from User_info where userName= @username and passWord=@password" Dim Params() As SqlParameter = {New SqlParameter("@username", user.user_name), New SqlParameter("@password", user.user_pwd)} Dim helper As New SqlHelper Dim dbuser = helper.GetDataTable(strSQL, CommandType.Text, Params) Return dbuser End Function End Class</span>
思想上移,行动下移——抽象工厂+反射+配置文件,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010926964/article/details/37053905