机房重构之七层登录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sophia_0331/article/details/81145746

我们常说的七层,那这七层是指哪七层呢?七层在三层就基础上增加了哪些层呢?七层就是在三层的基础上,添加了外观层——设计模式的外观模式,抽象工厂加反射,接口层。外观层主要是把UI层和BLL层分离;抽象工厂加反射主要是为了更换数据库的方便性,同时把DAL层中的类转换成IDAL层中的接口,从而使BLL层实现通过调用IDAL从而调用DAL层;接口层主要是为了把BLL层和DAL层分离。

一、七层的组成:

1、界面层(UI):主要用于收集用户输入的数据然后传给外观层,再由外观层传给B层进行相应的判断。

2、业务逻辑层(BLL):B层主要是进行逻辑判断的,调用工厂中的方法创建相应的接口。

3、数据访问层(DAL):实现接口层定义的接口。

4、外观层(Facade):运用外观层的目的是降低U层和B层之间的耦合,U层和B层之间的联系只需要通过Facade层的接口就行了,U层无需知道B层内部有哪些方法。外观层接收U层传来的数据,然后调用B层的方法对信息进行验证。

5、工厂层(Factory):通过配置文件和抽象工厂我们可以实现不更改代码,换一下配置文件中的value值就可以更换数据库了。Factory还需要完成的工作就是定义一个接口调用接口层,实现BLL层和DAL层之间的数据传递。

6、接口层(IDAL):接口层是用于定义一个统一的接口,解除B层和D层的耦合。

7、实体层(Entity):和三层中的实体层一样,主要是用来在各层中传递数据。

除此之外,还有SQLHelper,SQLHelper是从DAL层分离出来的。

SQLHelper:将D层中需要重复使用的连接数据库代码抽象到一个层里面了,这样就不用重复的写这些代码了,减少了冗余。

二、各层之间的关系如下:

各层代码如下:

UI层

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LoginUI
{
    public partial class UILogin : Form
    {
        public UILogin()
        {
            InitializeComponent();
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            //判断输入不能为空
            if (txtUserID.Text.Trim() == "")
            {
                MessageBox.Show("用户名不能为空","温馨提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);                
            }
            if (txtPWD.Text == "")
            {
                MessageBox.Show("密码不能为空","温馨提示",MessageBoxButtons.OK ,MessageBoxIcon.Warning);
            }
            try
            {
                Facade.LoginFacade Facade = new Facade.LoginFacade();
                Entity.UserInfo user = new Entity.UserInfo();
                user.UserID = Convert.ToInt32(txtUserID.Text.Trim());
                user.Password = txtPWD.Text;

                Boolean flag = false;
                Facade.LoginFacade FLogin = new Facade.LoginFacade();//实例化外观

                flag = FLogin.SelectUser(user);//调用外观的方法,返回给user

                if (flag != false)
                {
                    this.Hide();
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    frmMain frmMain = new frmMain();//实例化一个窗体
                    frmMain.Show();//显示实例化的窗体
                }
                else
                {
                    MessageBox.Show("密码或者用户名错误");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void btncancel_Click(object sender, EventArgs e)
        {
            
            System.Environment.Exit(0);

        }
    }
}

Facade层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Facade
{
    public class LoginFacade
    {
        public Boolean SelectUser(Entity.UserInfo user)
        {
            bool flag;
            BLL.LoginBLL userBLL = new BLL.LoginBLL();
            flag = userBLL.UserBLL(user);
            return flag;
        }
    }
}

BLL层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace BLL
{
    public class LoginBLL
    {
        public bool UserBLL(Entity.UserInfo UserInfo)
        {
            Facatory.LoginFactory fact = new Facatory.LoginFactory();//实例化工厂
            IDAL.LoginIDAL idal = fact.CreateUser();//调用工厂方法创建接口  
            DataTable table = idal.selectUser(UserInfo);//接受D层的返回值  
            bool flag;
            if (table.Rows.Count == 0)//返回的DataTable类型,如果它的行数等于0,说明没有符合该帐号密码的用户  
            { flag = false; }
            else
            {
                flag = true;
            }
            return flag;
        }
    }
}

Factory层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;//增加反射的引用
using System.IO;

namespace Facatory
{
    public class LoginFactory
    {
        string StrDB = System.Configuration.ConfigurationManager.AppSettings["DB"];

        public IDAL.LoginIDAL CreateUser()
        {
            string ClassName = StrDB + "." + "LoginDAL";//DAL层的类名
            return (IDAL.LoginIDAL)Assembly.Load(StrDB).CreateInstance(ClassName);
        }
    }
}

IDAL层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace IDAL
{
    public interface LoginIDAL
    {
        DataTable selectUser(Entity.UserInfo UserInfo);

    }
}

DAL层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class LoginDAL : IDAL.LoginIDAL
    {

        public DataTable selectUser(Entity.UserInfo UserInfo)
        {

            SQLHelper sqlHelper = new SQLHelper();
            SqlParameter[] sqlParams = { new SqlParameter("@userID", UserInfo.UserID), new SqlParameter("@Password", UserInfo.Password) };
            string sql = @"SELECT * FROM [User_Info] WHERE UserID=@UserID and PWD =@Password";
            DataTable table = sqlHelper.ExecuteQuery(sql, sqlParams, CommandType.Text);
            return table;

        }
    }
}

Entity层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Entity
{
    public class UserInfo
    {
        //定义 用户ID 字段
        private int? userid;
        public int? UserID
        {
            get { return userid; }
            set { userid = value; }
        }

        //定义 用户名 字段
        private string userName;
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        //定义 密码 字段
        private string password;
        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        //定义 等级 字段
        private string level;
        public string Level
        {
            get { return level; }
            set { level = value; }
        }

        //定义 状态 字段
        private bool state;
        public bool State
        {
            get { return state; }
            set { state = value; }
        }

    }
}

SQLHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;


namespace DAL
{
    public class SQLHelper
    {
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        private SqlDataReader sdr = null;



        public SQLHelper()
        {
            string connStr = ConfigurationManager.AppSettings["connstr"];//连接数据库,connstr是从web.config配置文件里面连接数据库的关键字,在每个.cs页面引用这一句就可以连接数据库
            conn = new SqlConnection(connStr);
        }

        private SqlConnection GetConn()
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            return conn;
        }

        /// <summary>
        /// 执行不带参数的的增删改SQL语句或者存储过程
        /// </summary>
        /// <param name="cmdText">增删改查SQL</param>
        /// <param name="ct">命令类型</param>
        /// <returns>返回受影响的行数</returns>
        /// 
        public int ExecuteNonQuery(string cmdText, CommandType ct)
        {
            int res;
            try
            {
                cmd = new SqlCommand(cmdText, GetConn());
                cmd.CommandType = ct;
                res = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            return res;
        }

        /// <summary>
        /// 执行带参数的的增删改SQL语句或者存储过程
        /// </summary>
        /// <param name="cmdText">增删改查SQL</param>
        /// <param name="paras">要查询的参数</param>
        /// <param name="ct">命令类型</param>
        /// <returns>返回受影响的行数</returns>
        /// 
        public int ExecuteNonQuery(string cmdText, SqlParameter[] paras, CommandType ct)
        {
            int res;
            using (cmd = new SqlCommand(cmdText, GetConn()))
            {
                cmd.CommandType = ct;
                cmd.Parameters.AddRange(paras);
                res = cmd.ExecuteNonQuery();
            }
            return res;
        }

        /// <summary>
        ///  执行不带参数的查询SQL语句或存储过程
        /// </summary>
        /// <param name="cmdText">查询SQL语句或存储过程</param>
        /// <param name="ct">命令类型</param>
        /// <returns></returns>
        /// 

        public DataTable ExecuteQuery(string cmdText, CommandType ct)
        {
            DataTable dt = new DataTable();
            cmd = new SqlCommand(cmdText, GetConn());
            cmd.CommandType = ct;
            using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                dt.Load(sdr);
            }
            return dt;

        }
        /// <summary>
        /// 执行带参数的查询SQL语句或存储过程
        /// </summary>
        /// <param name="cmdText">查询SQL语句或存储过程</param>
        /// <param name="paras">参数集合</param>
        /// <param name="ct">命令类型</param>
        /// <returns></returns>
        /// 
        public DataTable ExecuteQuery(string cmdText, SqlParameter[] paras, CommandType ct)
        {
            DataTable dt = new DataTable();
            cmd = new SqlCommand(cmdText, GetConn());

            cmd.CommandType = ct;
            cmd.Parameters.AddRange(paras);
            using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                dt.Load(sdr);
            }
            return dt;
        }

    }
}

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
  <appSettings>
    <add key ="ConnStr" value="server=.; database=SOPHIA\MSSQLSERVER1;user ID = sa ; pwd=123456"/>
    <!-- server是自己数据库的名字或者用.代表本地;把database,uid,pwd修改为与自己数据库对应的关系-->
    <add key ="DB" value="DAL" />
  </appSettings>
</configuration>

在敲七层登录时,明明添加了命名空间Using system.configuration,但是依然会报错显示找不到configurationManager。

解决方案如下:

在解决方案资源管理器中引用框架system.Configuration,然后再重新生成解决方案,问题就解决了。

猜你喜欢

转载自blog.csdn.net/Sophia_0331/article/details/81145746
今日推荐