CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Tìm hiểu Composite Design Pattern với ví dụ sử dụng ngôn ngữ C#

Đăng lúc: 09:30 AM - 20/12/2022 bởi Charles Chung - 647

Composite là một mẫu thuộc nhóm Structures Pattern. Nó là một sự tổng hợp những thành phần có quan hệ với nhau để tạo ra thành phần lớn hơn. Nó cho phép thực hiện các tương tác với tất cả đối tượng trong mẫu tương tự nhau.

1. Mục đích của Composite

Composite Pattern được sử dụng khi chúng ta cần xử lý một nhóm đối tượng tương tự theo cách xử lý 1 object. Composite pattern sắp xếp các object theo cấu trúc cây để diễn giải 1 phần cũng như toàn bộ hệ thống phân cấp. Pattern này tạo một lớp chứa nhóm đối tượng của riêng nó. Lớp này cung cấp các cách để sửa đổi nhóm của cùng 1 object. Pattern này cho phép Client có thể viết code giống nhau để tương tác với composite object này, bất kể đó là một đối tượng riêng lẻ hay tập hợp các đối tượng.

2. Cấu trúc của Composite

Giải thích các thành phần:

  • Component: là một interface hoặc abstract class quy định các method chung cần phải có cho tất cả các thành phần tham gia vào mẫu này.
  • Leaf: là lớp hiện thực (implements) các phương thức của Component - các object không có con.
  • Composite: lưu trữ tập hợp các Leaf và cài đặt các phương thức của Component. Composite cài đặt các phương thức được định nghĩa trong interface Component bằng cách ủy nhiệm cho các thành phần con xử lý.
  • Client: sử dụng Component để làm việc với các đối tượng trong Composite.

3. Ví dụ demo code C#

Tệp IEmployee.cs

namespace CompositePattern
{
    /// <summary>
    /// Component tree node
    /// </summary>
    public interface IEmployee
    {
        int EmpId { get; set; }
        string Name { get; set; }
    }
}

Tệp Employee.cs

namespace CompositePattern
{
    /// <summary>
    /// Composite class
    /// </summary>
    public class Employee : IEmployee, IEnumerable<IEmployee>
    {
        private List<IEmployee> _subordinates = new List<IEmployee>();

        public int EmpId { get; set; }
        public string Name { get; set; }

        public void AddSubordinate(IEmployee subordinate)
        {
            _subordinates.Add(subordinate);
        }

        public void RemoveSubordinate(IEmployee subordinate)
        {
            _subordinates.Remove(subordinate);
        }

        public IEmployee GetSubordinate(int index)
        {
            return _subordinates[index];
        }

        public IEnumerator<IEmployee> GetEnumerator()
        {
            foreach (IEmployee subordinate in _subordinates)
            {
                yield return subordinate;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

Tệp Contractor.cs

namespace CompositePattern
{
    /// <summary>
    /// Leaf class
    /// </summary>
    public class Contractor : IEmployee
    {
        public int EmpId { get; set; }
        public string Name { get; set; }
    }
}

Tệp Program.cs

namespace CompositePattern
{

    /// <summary>
    /// Client class
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Employee Rahul = new Employee { EmpId = 1, Name = "Rahul" };

            Employee Amit = new Employee { EmpId = 2, Name = "Amit" };
            Employee Mohan = new Employee { EmpId = 3, Name = "Mohan" };

            Rahul.AddSubordinate(Amit);
            Rahul.AddSubordinate(Mohan);

            Employee Rita = new Employee { EmpId = 4, Name = "Rita" };
            Employee Hari = new Employee { EmpId = 5, Name = "Hari" };

            Amit.AddSubordinate(Rita);
            Amit.AddSubordinate(Hari);

            Employee Kamal = new Employee { EmpId = 6, Name = "Kamal" };
            Employee Raj = new Employee { EmpId = 7, Name = "Raj" };

            Contractor Sam = new Contractor { EmpId = 8, Name = "Sam" };
            Contractor tim = new Contractor { EmpId = 9, Name = "Tim" };

            Mohan.AddSubordinate(Kamal);
            Mohan.AddSubordinate(Raj);
            Mohan.AddSubordinate(Sam);
            Mohan.AddSubordinate(tim);

            Console.WriteLine("EmpId={0}, Name={1}", Rahul.EmpId, Rahul.Name);

            foreach (Employee manager in Rahul)
            {
                Console.WriteLine("\n EmpId={0}, Name={1}", manager.EmpId, manager.Name);

                foreach (var employee in manager)
                {
                    Console.WriteLine(" \t EmpId={0}, Name={1}", employee.EmpId, employee.Name);
                }
            }
            Console.ReadKey();
        }
    }
}

Link download source code (Google Drive)

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ