码迷,mamicode.com
首页 > 其他好文 > 详细

业务逻辑层-Transaction Script

时间:2018-07-31 21:37:08      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:otc   pre   open()   取数   检查   default   tween   parameter   ext   

Transaction Script(事务脚本模式),是一种最简单和最容易接受的处理业务的方法。这种模式是采用面向过程的方式来组织业务逻辑。通常情况下,系统的一个流程会被实现为一个方法,然后所有的方法被组织在一起,放在一个类中。
设计思想:取数据-》逻辑-》数据展示。 存数据-》逻辑-》保存数据。

优点

  • 简单,对大多数开发者都可用理解
  • 一个事务的处理,不会影响到其他的事务

    缺点

    业务逻辑复杂时,系统每增加一个业务流程,代码就会增加一个或几个方法,最后业务类中存在大量相似的代码(重用性不强,难以维护)

    案例

    人事管理系统中的请假流程
  1. 判断员工提交的请假数据是否合法
  2. 检查提交请求的员工是否还有剩余假期
  3. 批准假期,并记录下来

    Code

    一般解决通过sql查询数据,在将查询结果赋值给交换对象。代码下载

    交换数据类

    /// <summary>
    /// 请假申请数据交换对象
    /// </summary>
    public class BookedLeaveDTO
    {
        public DateTime From { get; set; }
        public DateTime To { get; set; }
        public int DaysTaken { get; set; }
    }

    /// <summary>
    /// 员工数据对象
    /// </summary>
    public class EmployeeDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int HolidayEntitlement { get; set; }
    }

服务对象

    public class EmployeeService
    {
        private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        /// <summary>
        /// 添加员工
        /// </summary>
        /// <param name="name"></param>
        /// <param name="holidayEntitlement"></param>
        public static void CreateEmployee(string name, int holidayEntitlement)
        {
            string insertSql = "INSERT INTO Employees " +
                              "(Name, HolidayEntitlement) VALUES " +
                              "(@Name, @HolidayEntitlement); SELECT @@identity;";

            using (SqlConnection connection =
                   new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = insertSql;

                command.Parameters.Add(new SqlParameter("@Name", name));
                command.Parameters.Add(new SqlParameter("@HolidayEntitlement", holidayEntitlement));

                connection.Open();

                command.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 得到公司所有员工
        /// </summary>
        /// <returns></returns>
        public static List<EmployeeDTO> GetAllEmployees()
        {
            List<EmployeeDTO> employees = new List<EmployeeDTO>();

            string selectSql = "SELECT * FROM Employees;";

            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = selectSql;

                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        employees.Add(new EmployeeDTO
                        {
                            Id = int.Parse(reader["Id"].ToString()),
                            Name = reader["Name"].ToString(),
                            HolidayEntitlement = int.Parse(reader["HolidayEntitlement"].ToString())
                        });
                    }
                }
            }

            return employees;
        }
    }

    public class HolidayService
    {
        private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        /// <summary>
        /// 员工请假
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <returns></returns>
        public static bool BookHolidayFor(int employeeId, DateTime From, DateTime To)
        {
            bool booked = false;
            TimeSpan numberOfDaysRequestedForHoliday = To - From;

            if (numberOfDaysRequestedForHoliday.Days > 0)
            {
                if (RequestHolidayDoesNotClashWithExistingHoliday(employeeId, From, To))
                {
                    int holidayAvailable = GetHolidayRemainingFor(employeeId);

                    if (holidayAvailable >= numberOfDaysRequestedForHoliday.Days)
                    {
                        SumitHolidayBookingFor(employeeId, From, To);
                        booked = true;
                    }
                }
            }

            return booked;
        }
        
        /// <summary>
        /// 请假日期是否于法定假日冲突
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <returns></returns>
        private static bool RequestHolidayDoesNotClashWithExistingHoliday(int employeeId, DateTime From, DateTime To)
        {
            return true;
        }
        /// <summary>
        /// 剩余假期数
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        private static int GetHolidayRemainingFor(int employeeId)
        {
            List<BookedLeaveDTO> bookedLeave = GetBookedLeaveFor(employeeId);

            int daysTaken = bookedLeave.Sum(hol => hol.DaysTaken);
            int holidayEntitlement = GetHolidayEntitlementFor(employeeId);

            int daysRemaining = holidayEntitlement - daysTaken;

            return daysRemaining;
        }

        /// <summary>
        /// 期间内请假的所有员工
        /// </summary>
        /// <param name="From"></param>
        /// <param name="To"></param>
        /// <returns></returns>
        public static List<EmployeeDTO> GetAllEmployeesOnLeaveBetween(DateTime From, DateTime To)
        {
            // ... Example of Transaction Script Method ...
            throw new NotImplementedException();
        }

        /// <summary>
        /// 所有员工假期剩余天数
        /// </summary>
        /// <returns></returns>
        public static List<EmployeeDTO> GetAllEmployeesWithHolidayRemaing()
        {
            // ... Example of Transaction Script Method ...
            throw new NotImplementedException();
        }

        /// <summary>
        /// 批准请假
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="From"></param>
        /// <param name="To"></param>
        private static void SumitHolidayBookingFor(int employeeId, DateTime From, DateTime To)
        {
            string insertSql = "INSERT INTO Holidays (EmployeeId, LeaveFrom, LeaveTo) VALUES " +
                               "(@EmployeeId, @LeaveFrom, @LeaveTo);";

            using (SqlConnection connection =
                 new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = insertSql;

                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));
                command.Parameters.Add(new SqlParameter("@LeaveFrom", From));
                command.Parameters.Add(new SqlParameter("@LeaveTo", To));

                connection.Open();

                command.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 员工所请的假期
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public static List<BookedLeaveDTO> GetBookedLeaveFor(int employeeId)
        {
            List<BookedLeaveDTO> bookedLeave = new List<BookedLeaveDTO>();

            string selectSql = "SELECT * FROM Holidays WHERE EmployeeId = @EmployeeId;";

            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = selectSql;
                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));

                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        bookedLeave.Add(new BookedLeaveDTO
                        {
                            From = DateTime.Parse(reader["LeaveFrom"].ToString()),
                            To = DateTime.Parse(reader["LeaveTo"].ToString()),
                            DaysTaken = ((TimeSpan)(DateTime.Parse(reader["LeaveTo"].ToString()) - DateTime.Parse(reader["LeaveFrom"].ToString()))).Days
                        });
                    }
                }
            }

            return bookedLeave;
        }

        /// <summary>
        /// 员工剩余假期
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        private static int GetHolidayEntitlementFor(int employeeId)
        {
            string selectSql = "SELECT HolidayEntitlement FROM Employees WHERE Id = @EmployeeId;";

            int holidayEntitlement = 0;

            using (SqlConnection connection =
                 new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = selectSql;

                command.Parameters.Add(new SqlParameter("@EmployeeId", employeeId));

                connection.Open();

                holidayEntitlement = int.Parse(command.ExecuteScalar().ToString());
            }

            return holidayEntitlement;
        }
    }

业务逻辑层-Transaction Script

标签:otc   pre   open()   取数   检查   default   tween   parameter   ext   

原文地址:https://www.cnblogs.com/LoveTomato/p/9397561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!