1. 程式人生 > >業務邏輯層-Transaction Script

業務邏輯層-Transaction Script

存在 default 員工 數據對象 main tcl 維護 esc scala

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