很早之前,就聽說過三層結構了。當時只知道 三層結構 是把 系統的 界面 跟 數據庫操作等不相關的程序分別開來。原來這么簡單的實現,確實傳說中的 三層結構啊。
首先,先來看一下是哪三層。表示層(UI,User Interface),業務邏輯層(BLL BusinessLogicLayer),數據訪問層(DAL Data Access Layer)。三層的划分是物理上的划分。
表示層(UI),這個最容易理解,就是用戶看到的主界面。
數據訪問層(DAL),也不難理解,主要是負責數據的增刪改查。
業務邏輯層(BLL),算是表示層和數據訪問層的橋梁吧。里面主要存放一些業務流程。也就是邏輯。主要作用就是從DAL中獲取數據,然后顯示到UI上。
舉一個例子,三層結構可以用飯店的實例來理解。
UI 指的是服務員, BLL 是廚師, DAL 是采購員。
在顧客的眼里,只能看到服務員為他們服務。並不知道后台廚師和采購員 是如何做的。對於上述三種不同的角色來說,無論哪個環節出了問題,只需要更換一個員工就可以照常營業的。
三層架構的優勢,還是職責分離,降低耦合。
接下來,看一個使用三層結構的登陸實例。首先,需要聲明一下。這個實例中有很多 bug 需要優化。不過對於展示三層的主要思想足夠了。僅僅是一個實例而已。
數據庫表:
這是數據模塊圖:
細心的讀者肯定會發現,除了 UI,BLL,DAL 這三個之外還有一個 Moudel 存在,這個 Moudel 不屬於任何一層,只是為了更好地鏈接三層而存在的。這個類只存儲,與以上三類共同使用的東西。起一個 協調的作用。 Moudel 類,也就是實體類。
下面是這幾個層次的關系。
接下來需要看一下,他們分別是如何實現各自的分工的。
UserModel類:
namespace LoginModel { /// <summary> /// 實體類,用於保存用戶信息 /// </summary> public class UserModel { public int Id { get; set; } public string UserName { get; set; } public string UserPwd { get; set; } } }
UI層:
private void btnLogin_Click(object sender, EventArgs e) { try { ////取出用戶界面的數據 string userName = txtUserName.Text.Trim(); string userPwd = txtUserPwd.Text; UserBLL userBll = new UserBLL();//實例化一個業務邏輯層BLL UserModel userModel = userBll.UserLogin(userName, userPwd);//使用用戶界面數據,進行查找BLL數據 MessageBox.Show("登陸用戶:" + userModel.UserName); } catch (Exception ex) //如果登陸有異常 則登陸失敗 { MessageBox.Show(ex.Message); } }
BLL層:
namespace LoginBLL { /// <summary> /// //業務邏輯層 /// </summary> public class UserBLL { public UserModel UserLogin(string userName, string userPwd) { UserDAL userDal = new UserDAL();//實例化一個數據訪問層 UserModel user = userDal.SelectUser(userName, userPwd);////通過ui中填寫的內容 返回來相應的數據 if (user != null) { return user;//如果數據庫中有數據,則返回一個實體類 } else { throw new Exception("登陸失敗"); } } } }
DAL層:
UserDAL類:
namespace LoginDAL { public class UserDAL { ////根據 ui 選擇返回一個user public UserModel SelectUser(string userName, string userPwd) { using (SqlConnection conn = new SqlConnection(DbUtil.connString)) { //創建一個命令對象,並添加命令 SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = @"select Id,UserName,UserPwd from T_UserInfo where UserName=@UserName and UserPwd=@UserPwd"; cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@UserName",userName); cmd.Parameters.AddWithValue("@UserPwd", userPwd); conn.Open();//打開數據鏈接 SqlDataReader reader = cmd.ExecuteReader(); UserModel user = null; //用於保存讀取的數據 while (reader.Read()) //開始讀取數據 { if (user == null) //如果沒有,則重新生成一個 { user = new UserModel(); } user.Id = reader.GetInt32(0); user.UserName = reader.GetString(1); user.UserPwd = reader.GetString(2); } return user; } } } }
DbUtil類:
namespace LoginDAL { /// <summary> /// //數據訪問層,用於保存 鏈接服務器的sql語句 /// </summary> class DbUtil { public static string connString = @"Server=xxx;Database=xx;User ID=sa; Password=123"; } }