重构机房收费系统时,刚开始用三层敲写,完成后觉得很多东西没用到,比如外观模式,抽象工厂加反射等,因此又推翻了重新敲写七层,各种参数的传递刚开始确实有些不明白,经过一段时间的查资料和摸索之后有了些感觉。
七层其实就是在远在三层框架的基础上添加了接口(IDAL),工厂(Factory),外观(Facade),以及贯穿始终的实体层(Entity)。由于已经有不少大神做的七层包图,在此也就不再展示。
首先:实体层(Entity)
实体对象实际上是对应着数据库里的每张表的,我们把表里的字段封装在1个实体对象里 当你想用哪个字段 你就就通过该实体对象的get() set() 把那个字段提取出来 这比你临时创建1个变量要灵活的多 而且便于程序的维护和扩展.在实际的3层结构开发中,专门有个实体层,他的作用就是便于层和层之间的数据传递。
登录中,我用UserEntity对应数据库中的T_User表,也就是用户基本信息表。
'用户实体类,对应T_User表 Public Class UserEntity Private _id As String Private _password As String Private _username As String Private _level As String Private _Head As String Public Property ID() As String Get Return _id End Get Set(value As String) _id = value End Set End Property Public Property Password() As String Get Return _password End Get Set(value As String) _password = value End Set End Property Public Property UserName() As String Get Return _username End Get Set(value As String) _username = value End Set End Property Public Property Level() As String Get Return _level End Get Set(value As String) _level = value End Set End Property Public Property Head() As String Get Return _Head End Get Set(value As String) _Head = value End Set End Property End ClassUserEntity中的每个字段对应了T_User表中的每个字段。
对应代码如下
<span style="font-size:18px;">Public Class frmLoginUI Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click '把用户名和密码放到一个实体中 Dim user As New Entity.UserEntity user.ID = txtUsername.Text.Trim() user.Password = txtPassword.Text Dim LoginUI As New Facade.LoginFac Dim strResult As String strResult = LoginUI.login(user) '用户名和密码验证的几种情况 Select Case strResult Case "此用户不存在" MsgBox("此用户不存在,请重新输入用户名!") txtUsername.Focus() txtUsername.SelectAll() Case "密码错误" MsgBox("密码错误,请重新输入!") txtPassword.Focus() txtPassword.SelectAll() Case "登陆成功" frmMain.Show() Me.Close() End Select End Sub Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click End End Sub End Class</span>
<span style="font-size:18px;">Public Class LoginFac Public Function login(ByVal user As Entity.UserEntity) As String Dim ConfirmUserBLL As New BLL.ConfirmUser '调用B层方法验证用户名和密码是否存在 If Not ConfirmUserBLL.IsExits(user) Then Return "此用户不存在" Else If Not ConfirmUserBLL.ConfirmPWD(user) Then Return "密码错误" Else Return "登陆成功" End If End If End Function End Class</span>
<span style="font-size:18px;">Imports IDAL Public Class ConfirmUser '验证用户名是否正确 Public Function IsExits(ByVal user As Entity.UserEntity) As Boolean Dim Iuser As IDAL.IUser Dim factory As New Factory.DBFactory Dim Iworklog As IDAL.IWorklog Iuser = factory.CreateUserDAO() Iworklog = factory.CreateWorklog() Dim table As New DataTable table = Iuser.SelectUser(user) If table.Rows.Count = 0 Then Return False Else Return True End If End Function '验证密码是否正确 Public Function ConfirmPWD(ByVal password As Entity.UserEntity) As Boolean Dim Iuser As IDAL.IUser Dim factory As New Factory.DBFactory Iuser = factory.CreateUserDAO Dim table As New DataTable table = Iuser.SelectUser(password) If table.Rows.Count = 0 Then Throw New Exception("输入的密码不正确") Return False Else Return True End If End Function End Class </span>
<span style="font-size:18px;">'抽象工厂,负责数据库的选择和创建接口 Imports System.Reflection Imports System.Configuration Imports IDAL Public Class DBFactory Dim strDB As String = System.Configuration.ConfigurationSettings.AppSettings("DB") Private Shared ReadOnly assemblyName = "DAL" Public Function CreateUserDAO() As IDAL.IUser Dim className As String = assemblyName + "." + "UserDAL" Return CType(Assembly.Load(assemblyName).CreateInstance(className), IDAL.IUser) '返回IUser End Function End Class </span>
<span style="font-size:18px;">mports System.Data.DataTable Public Interface IUser Function SelectUser(ByVal User As Entity.UserEntity) As System.Data.DataTable End Interfac </span>
D层用来将接口实例化
<span style="font-size:18px;">Imports System.Data.SqlClient Public Class UserDAL : Implements IDAL.IUser Public Function SelectUser(ByVal User As Entity.UserEntity) As System.Data.DataTable Implements IDAL.IUser.SelectUser Dim sqlParams As SqlParameter() = {New SqlParameter("@UserID", User.ID), New SqlParameter("@Password", User.Password)} Dim strSql As String = "select * from T_User where UserID=@UserID" Dim helper As New SqlHelper '实例化SqlHelper 'Dim cmdType As CommandType = New CommandType() 'cmdType = CommandType.StoredProcedure '定义命令类型为存储过程 Dim table As New DataTable table = helper.GetDataTable(strSql, CommandType.Text, sqlParams) Return table End Function End Class </span>我将SqlHelper放到了D层
开始不明白什么是SqlHelper,后来查阅了一些资料,加上编写应用实例,现在明白些。
SqlHelper用于简化你重复的去写那些数据库连接(SqlConnection),SqlCommand,SqlDataReader等等。SqlHelper 封装过后通常是只需要给方法传入一些参数如数据库连接字符串,SQL参数等,就可以访问数据库了,很方便。
<span style="font-size:18px;">Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Reflection Public Class SqlHelper '利用配置文件寻找“连接字符串”,建立cmd文件 Private ReadOnly constr As String = System.Configuration.ConfigurationSettings.AppSettings("strConn") Dim conn As New SqlConnection(constr) Dim cmd As New SqlCommand ''' <summary> ''' 带参数,返回结果是表 ''' </summary> ''' <param name="cmdTxt"></param> ''' <param name="cmdType"></param> ''' <param name="sqlparams"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function GetDataTable(ByVal cmdTxt As String, ByVal cmdType As CommandType, ByVal sqlparams As SqlParameter()) As DataTable cmd = conn.CreateCommand() '利用传进的参数填充cmd对象 cmd.CommandText = cmdTxt cmd.CommandType = cmdType cmd.Parameters.AddRange(sqlparams) Dim sqlAdapter As New SqlDataAdapter(cmd) '定义数据适配器变量,并实例化,将cmd绑定在adaptor上面 Dim dsSQL As New DataSet '定义数据缓存变量 Try conn.Open() sqlAdapter.Fill(dsSQL) '用adapter将dataset填充 Return dsSQL.Tables(0) Catch ex As Exception Return Nothing MsgBox(ex.Message, , "数据库操作") Finally Call closeConn(conn) End Try End Function ''' <summary> ''' 不带参数,返回结果是表 ''' </summary> ''' <param name="cmdTxt"></param> ''' <param name="cmdType"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function GetDataTable(ByVal cmdTxt As String, ByVal cmdType As CommandType) As DataTable cmd = conn.CreateCommand() '利用传进的参数填充cmd对象 cmd.CommandText = cmdTxt cmd.CommandType = cmdType 'Dim dtSQL As New DataTable '定义数据表格 Dim sqlAdapter As New SqlDataAdapter(cmd) '定义数据适配器变量,并实例化,将cmd绑定在adaptor上面 Dim dsSQL As New DataSet '定义数据缓存变量 Try conn.Open() sqlAdapter.Fill(dsSQL) '用adapter将dataset填充 Return dsSQL.Tables(0) Catch ex As Exception MsgBox(ex.Message, , "数据库操作") Finally Call closeConn(conn) End Try Return dsSQL.Tables(0) End Function ''' <summary> ''' 带参数,返回结果是值 ''' </summary> ''' <param name="cmdTxt"></param> ''' <param name="cmdType"></param> ''' <param name="sqlparams"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function ExecuteNonQuery(ByVal cmdTxt As String, ByVal cmdType As CommandType, ByVal sqlparams As SqlParameter()) As Integer cmd = conn.CreateCommand() Dim sqlAdapter As New SqlDataAdapter(cmd) Dim dsSQL As New DataSet '利用传进的参数填充cmd对象 cmd.CommandText = cmdTxt cmd.CommandType = cmdType cmd.Parameters.AddRange(sqlparams) Try conn.Open() sqlAdapter.Fill(dsSQL) Return dsSQL.Tables.Count Catch ex As Exception Return Nothing MsgBox(ex.Message, , "数据库操作") Finally Call closeConn(conn) End Try End Function ''' <summary> ''' 不带参数,返回结果是值 ''' </summary> ''' <param name="cmdTxt"></param> ''' <param name="cmdType"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function ExecuteNonQuery(ByVal cmdTxt As String, ByVal cmdType As CommandType) As Integer cmd = conn.CreateCommand() Dim dsSQL As New DataSet '利用传进的参数填充cmd对象 cmd.CommandText = cmdTxt cmd.CommandType = cmdType Dim sqlAdapter As New SqlDataAdapter(cmd) Try conn.Open() 'int = cmd.ExecuteNonQuery() sqlAdapter.Fill(dsSQL) Catch ex As Exception MsgBox(ex.Message, , "数据库操作") Finally Call closeConn(conn) End Try 'Return int Return dsSQL.Tables.Count End Function '关闭数据库连接 Public Shared Sub closeConn(ByVal conn As SqlConnection) If conn.State = ConnectionState.Open Then conn.Close() End If End Sub End Class</span>SqlHelper支持多种数据库包括MySql、SqlServer、Oracle、Access数据库,如果数据库是SqlServer,那么你可以使用SqlServerHelper类,如果是MySql,可以使用MySqlHelper,如果是Access,可以使用AccessHelper。如果是Oracle则可以使用OracleHelper类。