上篇简单介绍了我对三层的认识:
http://blog.csdn.net/onlybymyself/article/details/43645813
这次关于登录:练习了两个版本:VB.NET和C#
在练习过程中,还了解了实体层:
为更好地满足引用原则:
1 DAL不引用BLL和UI;
2 BLL需要引用DAL;
3 UI直接引用BLL,可能间接引用DAL;
4 避免互相引用。
引进:实体层
关于实体层,可以将其理解为:装载数据的容器或一个载体。
因为有些数据,所有层都要用,但又要避免相互引用,这就可以用实体层来解决~~~
关于登录,以.NET为例:
具体实现:
输入正确用户名、密码:
输入错误用户名或密码:
点击取消:退出程序
数据库设计:建一个用户名、密码表即可(简单小登录)
VS中:
DAL层:只提供基本的数据访问,不包含任何业务相关的逻辑处理。
'引用命名空间
Imports System.Data.SqlClient
Imports LoginEntity
Public Class UserDAO
'连接数据库
Dim sqlConnectStr As String = "server=zhaohan;database=Login;uid=sa;pwd=123456;"
Dim sqlConnection1 As SqlConnection = New SqlConnection(sqlConnectStr) 'SqlConnection:重新连接
'自定义检查参数
Function selectUserInfoFormUserInfoTable(ByVal User As LoginEntity.e_UserInfo) As LoginEntity.e_UserInfo
Dim sql As String = "select * from UserInfo where UserID='" & User.UserID & "'"
Dim cmd As SqlCommand = New SqlCommand(sql, sqlConnection1) '定义sqlcommand对象
Dim read As SqlDataReader '定义sqldatareader对象
Dim User1 As New LoginEntity.e_UserInfo
Dim UserDataTable As New DataTable
Try
sqlConnection1.Open()
read = cmd.ExecuteReader()
UserDataTable.Load(read)
User1.UserID = UserDataTable.Rows(0)("UserID")
User1.Password = UserDataTable.Rows(0)("UserPassword")
Return User1
Catch ex As Exception
User1.Password = ""
Return User1
Finally
If Not IsNothing(sqlConnection1) Then
sqlConnection1.Close()
End If
End Try
End Function
End Class
BLL层: 负责处理业务逻辑。通过获取UI传来的操作指令,决定执行业务逻辑,在需要访问数据源的时候直接交给DAL处理。处理完成后,返回必要数据给UI.
Imports LoginEntity
Imports LoginDAL.UserDAO
Public Class LoginManager
Function SelectUIandEntity(ByVal User As LoginEntity.e_UserInfo) As Boolean
Dim DalUser As New LoginDAL.UserDAO
Dim EntityUser As New LoginEntity.e_UserInfo
EntityUser.UserID = User.UserID
EntityUser = DalUser.selectUserInfoFormUserInfoTable(EntityUser)
'判断操作
If EntityUser.Password = User.Password Then
Return True
Else
Return False
End If
End Function
End Class
UI层: 只负责显示和采集用户操作,不包含任何的业务相关的逻辑处理。
Public Class UserLogin
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnOk.Click
Dim LoginUser As New LoginEntity.e_UserInfo '定义LoginEntity.e_UserInfo对象
Dim Bcheck As New LoginBll.LoginManager '定义LoginBLL.LoginManager对象
LoginUser.UserID = txtUserName.Text
LoginUser.Password = txtPassword.Text
'采集用户信息,展现登录结果
If Bcheck.SelectUIandEntity(LoginUser) Then
MsgBox("登录成功")
Else
MsgBox("登录失败")
End If
End Sub
'退出系统
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
End
End Sub
End Class
小结:
通过学习三层,再敲一遍机房收费。同样的需求,不同的实现方式,让我们慢慢领悟码农和工程师的区别......