Responsibilities and use of each layer of the three-tier structure (Introduction)

table of Contents

Preface

concept:

Presentation layer (UI):

Business Logic Layer (BLL)

Data Access Layer (DAL):

Entity class library (Model):

Code display:

Presentation layer (UI):

Business logic layer (BLL):

Data Access Layer (DAL):

Entity class library (Model):

The above content is my understanding of the three-tier architecture. The code comments are my personal understanding. If you have any questions, please feel free to comment below!


Preface

The three-tier architecture is to comply with the idea of ​​"high cohesion, low coupling" and divide the entire business application into a three-tier structure, namely presentation layer (UI), business logic layer (BLL), data access layer (DAL), and Entity class library (Model), but how to implement the specific code, which code should be written in which layer, but it is vague, today I will share my feelings, I hope it can be helpful to you. First we understand the concepts and responsibilities of each layer:

concept:

Presentation layer (UI):

The presentation layer, also known as the presentation layer, is located at the top of the three-tier architecture. It has direct contact with users. Its main function is to realize the input and output of system data, and transmit the data directly to the BLL layer for data processing. The processing result is fed back to the presentation layer. Simply put, the presentation layer is to implement user interface functions and convey and feedback user needs.

Business Logic Layer (BLL)

The business logic layer BLL is the core of the software system. It is located between the presentation layer and the data access layer. It is the bridge between the presentation layer and the data access layer. The main function is to make logical judgments and perform operations on specific problems, and receive users who receive the presentation layer UI. After the instruction, the business logic is executed, the data source is written through the data access layer DAL, and the data is obtained from the DAL for UI display.

Data Access Layer (DAL):

The data access layer is the operation of the data, but not the database, because the data BLL layer of the DAL layer is passed in, and then the incoming data is written to the database, specifically for the presentation layer and business logic layer.

Entity class library (Model):

The entity class library is the mapping object of the database. In the actual development process of the information system software, an instance of the object must be established, and the relational database table shall be expressed in the form of object materialization to assist the control and operation of each system function in the software development. , And use Get and Set to map all the fields in the database table to system objects, establish an entity class library, and then realize the parameter transmission of each structural layer.

Code display:

Let's take a small login example as an example to show how the third layer is used. When the user logs in successfully, 10 points will be added to the user.

Presentation layer (UI):

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();//初始化组件,加载窗体
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
           
            string userName = txtUserName.Text.Trim();//获取输入的userName
            string password = txtPassword.Text;//获取输入的password
            Login.BLL.LoginManager mgr = new Login.BLL.LoginManager();//调用B层的登录方法,从B层返回user的信息
            Login .Model.UserInfo user = mgr.UserLogin(userName, password);//通过Model层,使用UserName、passwor

            MessageBox.Show("登录用户:" + user.UserName);//提示用户成功
        }
    }

Business logic layer (BLL):

public class LoginManager
    {
        public Login.Model.UserInfo UserLogin(string userName, string password)//执行Login操作,UI传来的指令UserLogin和传来的数据username、password,返回UserInfo
        {
            #region 判断登录的逻辑
            // throw new NotImplementedException();//访问数据源
            Login.DAL.UserDAO uDao = new Login.DAL.UserDAO();//呼叫DAL,实例化UserDAO,获取信息
            Login.Model.UserInfo user = uDao.SelectUser(userName, password);//调用UserDAO的查询方法,传两个值,返回UserInfo

            if (user != null)//判断User是否登录成功

            {
                Login.DAL.ScoreDAO sDao = new Login.DAL.ScoreDAO();//成功,调用ScoreDAO的方法增加积分
                sDao.UpdateScore(userName, 10);//更新积分,给用户加10分
                return user;//返回user
            }
            else
            {
                throw new Exception("登录失败");//失败,抛出异常
            }
            #endregion
        }
    }

Data Access Layer (DAL):

public class UserDAO//数据访问层,访问User表
    {
        public Login.Model.UserInfo SelectUser(string userName, string password)//判断用户是否存在的方法
        {
            using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))//获取SqlConnection,通过DBUtil得到Connstring,Using使Connection自动关闭
            {
                SqlCommand cmd = conn.CreateCommand();//创建Command
                cmd.CommandText = @"SELECT ID,UserName, Password,Email
                                    FROM Users WHERE UserName = @UserName AND Password=@Password";//执行SQl语句,查询数据
                cmd.CommandType = CommandType.Text;//默认值
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));//因为上面使用了参数,所以增加两个参数
                cmd.Parameters.Add(new SqlParameter("@Password", password));
                conn.Open();//打开链接,Using使Connection自动关闭链接
                SqlDataReader reader = cmd.ExecuteReader();

                Login.Model.UserInfo user = null;//构造User

                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);//not suggestion
                    if (!reader.IsDBNull(3))//Email可以为空,判断Email是不是为空
                    {
                        user.Email = reader.GetString(3);
                    }                   
                }
                return user;//返回User
            }            
        }
    }
/// <summary>
/// 积分类
/// </summary>
    public class ScoreDAO       //DAO数据访问对象,访问Score表
    {
        public void UpdateScore(string userName, int value)//判断增加积分的方法
        {
            using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))//通过Dbutil传字符串
            {
                SqlCommand cmd = conn.CreateCommand();//创建cmd
                cmd.CommandText = @"INSERT INTO Scores(UserName, Score) values(@UserName,@Score)";//向Score表中插入积分
                //cmd.Parameters.Add(new SqlParameter("@ID",value));
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));//构造两个参数
                cmd.Parameters.Add(new SqlParameter("@Score", value));

                conn.Open();//打开链接,Using自动关闭链接
                cmd.ExecuteNonQuery();//向数据库中插入数据
            }
        }
    }

Entity class library (Model):

/// <summary>
    /// 数据类库,封装数据,在三层之间传输数据
    /// 不引用任何一个层次的程序集,独立于三层之外
    /// 任何一层都要引用Model
    /// </summary>
    public class UserInfo//数据模型类UserInfo
    {
        public int ID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
    }

The above content is my understanding of the three-tier architecture. The code comments are my personal understanding. If you have any questions, please feel free to comment below!

Guess you like

Origin blog.csdn.net/TGB_Tom/article/details/109445849