在学习UML的时候,为了更加深刻的理解类图和包图,就提前学习了一些“三层”的知识,当时还没有面向对象的语言基础,只是大概的知道而已,并没有深入的去研究。
现在经过了C#,设计模式,VB.NET的学习,与“面向对象”进行了多次碰撞,这次就是用C#语言做了一个运用三层的小Demo,下面就详细的介绍一下三层的“3W1H”。
首先我们先来看第一个“W”,什么是三层架构?
namespace Login.DAL { public class UserDAO { public Login.Model.UserInfo SelectUser(string userName,string password) { using(SqlConnection conn=new SqlConnection (DbUtil.Connntring )) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = @"SELECT ID,UserName,PWD,Email FROM USERS WHERE Username=@Username AND PWD=@Password"; cmd.CommandType = CommandType.Text; cmd.Parameters.Add (new SqlParameter("@Username", userName)); cmd.Parameters .Add (new SqlParameter ("@Password",password)); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); Login.Model.UserInfo user = null; while (reader.Read ()) { if(user==null ) { user = new Login.Model.UserInfo(); } user.ID = reader.GetInt32(0); user.UserName = reader.GetString(1); user.PassWord = reader.GetString(2); if (!reader.IsDBNull (3)) { user.Email = reader.GetString(3); } } return user; } } } }
namespace Login.DAL { public class DbUtil { public static string Connntring = @"Server=AZZ-PC;Database=AZZ_Charge;User ID=sa;Password=123456"; } }
namespace Login.BLL { public class LoginManager { public Login.Model.UserInfo UserLogin(string userName,string password) { Login.DAL.UserDAO uDao = new Login.DAL.UserDAO(); Login.Model.UserInfo user=uDao.SelectUser(userName, password); if (user !=null ) { Login.DAL.ScoreDAO sDao=new Login.DAL.ScoreDAO(); sDao.UpdateScore(userName,10); return user; } else { throw new Exception ("登陆失败。"); } } } }
namespace Login.Model { public class UserInfo { public int ID { get; set; } public string UserName { get; set; } public string PassWord { get; set; } public string Email { get; set; } } }
namespace LoginUI { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { //IDbConnection conn = new SqlConnection("c......"); //IDbCommand cmd = conn.CreateCommand(); //cmd.CommandText = "Select UserName Form USERS WHERE"; //cmd.ExecuteReader(); string userName = txtUsername.Text.Trim(); string password = txtPassword.Text; Login.BLL.LoginManager mgr = new Login.BLL.LoginManager(); Login.Model.UserInfo user = mgr.UserLogin(userName, password); MessageBox.Show("登陆用户:" + user.UserName); } } }