Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts

2016-12-26

Castle Windsor Part 2 - Array configuration, dictionary configuration

Xem original

Part 2 – Array Configuration
Part 3 – Dictionary configuration

Array configuration

Đầu tiên là config array.

Ví dụ holiday service có code như sau:
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using System;

namespace ConsoleApp
{
    public class HolidayService
    {
        private DateTime[] holidays;

        public DateTime[] Holidays
        {
            get { return holidays; }
            set { holidays = value; }
        }

        public bool IsHoliday(DateTime date)
        {
            if (holidays != null)
            {
                DateTime matchDate = date.Date;
                foreach (DateTime dt in Holidays)
                {
                    if (dt.Date.Equals(matchDate))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer(new XmlInterpreter());

            HolidayService holidayService = container.Resolve<HolidayService>();

            DateTime xmas = new DateTime(2016, 12, 25);
            DateTime newYears = new DateTime(2017, 1, 1);

            if (holidayService.IsHoliday(xmas))
            {
                Console.WriteLine("Merry X'mas!");
            }
            else
            {
                Console.WriteLine("X'mas is only for management!");
            }

            if (holidayService.IsHoliday(newYears))
            {
                Console.WriteLine("Happy new year!");
            }
            else
            {
                Console.WriteLine("New year, you haven't done all the work for last year!");
            }

            Console.ReadLine();
        }
    }
}
Config trong App.config như sau:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component type="ConsoleApp.HolidayService, ConsoleApp">
        <parameters>
          <holidays>
            <array>
              <item>2016-12-24</item>
              <item>2016-12-25</item>
              <item>2017-1-1</item>
            </array>
          </holidays>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Có thể dùng <Holidays> hoặc <holidays> đều được vì Windsor đủ smart để inject. Nếu muốn resolve trực tiếp ra IList (hoặc IList, IEnumerable ... nói chung là generic collection)
static void Main(string[] args)
{
    WindsorContainer container = new WindsorContainer(new XmlInterpreter());
    var holidays = container.Resolve<IList<DateTime>>("holidays");
    Console.WriteLine(string.Join("\r\n", holidays));
    Console.ReadLine();
}
File config tương ứng như sau:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="holidays" type="System.Collections.Generic.List`1[System.DateTime]">
        <parameters>
          <collection>
            <array>
              <item>2016-12-24</item>
              <item>2016-12-25</item>
              <item>2017-1-1</item>
            </array>
          </collection>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>

Cần nhớ ở dạng config này là thực hiện theo <parameters><collection><array><item>. Nếu đầy đủ hơn thì type chỉ định có cả assembly là <component id="holidays" type="System.Collections.Generic.List`1[[System.DateTime, mscorlib]], mscorlib">.

Dictionary configuration

Tương tự như array, dictionary configuration thực hiện với <parameters><dictionary><dictionary><entry>. Ví dụ AliasService như sau:
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    public class AliasService
    {
        private Dictionary<string, string> dict;

        public Dictionary<string, string> Aliases
        {
            get { return dict; }
            set { dict = value; }
        }

        public string Evaluate(string term)
        {
            if (dict == null)
            {
                return term;
            }

            while (dict.ContainsKey(term))
            {
                term = dict[term];
            }

            return term;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer(new XmlInterpreter());

            AliasService aliasService = container.Resolve<AliasService>();
            string sentence = "A dog ate my homework";

            foreach (string word in sentence.Split(new char[] { ' ' }, 
                StringSplitOptions.RemoveEmptyEntries))
            {
                Console.Write("{0} ", aliasService.Evaluate(word));
            }

            Console.ReadLine();
        }
    }
}
App.config cấu hình dictionary:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component type="ConsoleApp.AliasService, ConsoleApp">
        <parameters>
          <Aliases>
            <dictionary>
              <entry key="dog">duck</entry>
              <entry key="ate">broke</entry>
              <entry key="homework">code</entry>
            </dictionary>
          </Aliases>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Để resolve trực tiếp ra IDictionary
static void Main(string[] args)
{
    WindsorContainer container = new WindsorContainer(new XmlInterpreter());
    var states = container.Resolve<IDictionary<string, string>>("states");
    Console.WriteLine(string.Join("\r\n", states.Keys));
    Console.ReadLine();
}
File config tương ứng như sau:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="states" type="System.Collections.Generic.Dictionary`2[System.String, System.String]">
        <parameters>
          <dictionary>
            <dictionary>
              <entry key="VN-CT">Cần Thơ</entry>
              <entry key="VN-DN">Đà Nẵng</entry>
              <entry key="VN-HN">Hà Nội</entry>
              <entry key="VN-HP">Hải Phòng</entry>
              <entry key="VN-SG">Hồ Chí Minh</entry>
            </dictionary>
          </dictionary>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Tới đây là xong part 2. Về type convertor có thể tham khảo thêm phần Configuration with type converters trong series của Mike Hadlow '10 Advanced Windsor tricks'.

Container tutorials ... example with Castle Windsor. Part 1 - Configuration parameters.

Mình dùng Castle Windsor từ lâu. Cũng có note nhưng rồi để đâu mất. Mình đã tính viết 1 series làm sao đủ để xài Windsor từ cái thời còn dùng CAB/SCSF, sau đó là Prism nhưng rồi chẳng biết sao lúc đó bỏ nửa chừng.

Inversion of Control (IoC), Dependency Inversion Principle (DIP) và Dependency Injection (DI), CAB&SCSF cũng chỉ viết tới Part 03: Dependency Injection

Gần đây coi lại và thấy lần này nên note kỹ. Nói chung đầu tiên là lược dịch từ những tutorials trên NET bắt đầu từ series trên BitterCoder (đã rất lâu rồi từ tận 2007). Có thể đọc thêm hướng dẫn từ project chính thức trên Github castleproject/Windsor.

Gần đây có nhiều lựa chọn IoC container cho .NET gồm có Autofac, StructureMap, Unity. Một vài container có vẻ dần chiếm được nhiều quan tâm hơn như Autofac với simple API, dễ sử dụng và performance tốt. Tuy nhiên Windsor nói chung vẫn đáp ứng được yêu cầu đặt ra với nhiều module (facilities) từ logging, NHibernate, ASP.NET MVC ...

Configuration parameters

Part đầu tiên là configuration parameters. Windsor cho phép cấu hình component với parameters run-time. Mặc dù có thể configuration với .NET qua app.config bình thường nhưng sử dụng với Windsor khá là đơn giản và tiện dụng.

Tạo một Project ConsoleApp, dùng NuGet install Castle Windsor. Tạo file app.config.


Giả sử có một class là Tax, mặc định tax rate là 10%. Có thể config rate thông qua app.config.
public class Tax
{
    private decimal rate = 0.10m;

    public decimal Rate
    {
        set { rate = value; }
        get { return rate; }
    }

    public decimal Calculate(decimal gross)
    {
        return Math.Round(rate * gross, 2);
    }
}
Sau khi tạo class Tax, thực hiện dùng với Windsor như sau:
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using System;

namespace ConsoleApp
{
    public class Tax
    {
        private decimal rate = 0.10m;

        public decimal Rate
        {
            set { rate = value; }
            get { return rate; }
        }

        public decimal Calculate(decimal gross)
        {
            return Math.Round(rate * gross, 2);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer(new XmlInterpreter());

            // Resolve
            Tax calculator = container.Resolve<Tax>();

            decimal gross = 100;
            decimal tax = calculator.Calculate(gross);

            Console.WriteLine("Gross: {0}, Tax: {1}", gross, tax);
            Console.ReadLine();
        }
    }
}
Container được tạo với XmlInterpreter() sẽ đọc configuration từ file app.config (hoặc web.config với web app), instance calculator được tạo bởi container thông qua Resolve().

Thực hiện Build và Run sẽ ra báo lỗi không có config section 'castle'.
Thực hiện thêm config section vào App.config. Giả sử App.config không có cấu hình component sẽ gây exception ComponentNotFoundException
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Thực hiện config component nhưng không set tax rate như sau
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="tax" type="ConsoleApp.Tax, ConsoleApp">
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Type có thể không cần dùng AssemblyQualifiedName mà để đơn giản là Tax hoặc ConsoleApp.Tax cũng OK. Kết quả trả ra 'Gross: 100, Tax: 10.00'.

Thực hiện setup rate bằng parameters như sau:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="tax" type="ConsoleApp.Tax, ConsoleApp">
        <parameters>
          <rate>0.25</rate>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
Kết quả trả ra 'Gross: 100, Tax: 25.00'.

Với id="tax" có thể dùng để resolve component khác nhau, ví dụ:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="tax1" type="ConsoleApp.Tax, ConsoleApp">
        <parameters>
          <rate>0.25</rate>
        </parameters>
      </component>
      <component id="tax2" type="ConsoleApp.Tax, ConsoleApp">
        <parameters>
          <rate>0.05</rate>
        </parameters>
      </component>
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  </startup>
</configuration>
và code
WindsorContainer container = new WindsorContainer(new XmlInterpreter());
decimal gross = 100;

// Resolve tax #1
Tax calculator1 = container.Resolve<Tax>("tax1");
decimal tax1 = calculator1.Calculate(gross);
Console.WriteLine("Gross: {0}, Tax: {1}", gross, tax1);

// Resolve tax #2
Tax calculator2 = container.Resolve<Tax>("tax2");
decimal tax2 = calculator2.Calculate(gross);
Console.WriteLine("Gross: {0}, Tax: {1}", gross, tax2);

Console.ReadLine();
Như vậy coi như là đủ cho part 1. Phần tiếp theo sẽ thực hiện config arrays, dictionary ...

2010-02-26

Inversion of Control (IoC), Dependency Inversion Principle (DIP) và Dependency Injection (DI)


Inversion of Control (IoC), Dependency Inversion và Dependency Injection

Mục tiêu giới thiệu Inversion of Control (IoC), Dependency Inversion và mối liên quan giữa 2 khái niệm này với Dependency Injection.

Trên Wikipedia và trong series của Rich cũng không define chính xác IoC là gì. Inversion of Control ý muốn đề cập tới các software architecture designs có flow of control ngược với kiến trúc cũ dạng software libraries (traditional architecture of software libraries). Không có gì ghê gớm cả ... :D, cứ cố hiểu đơn giản vậy là được. Trên blog của Martin Flower cũng có một bài viết khá hay 'Inversion of Control Containers and the Dependency Injection pattern', nếu có thời gian thì bạn có thể tham khảo để biết quan điểm của một người chuyên nghiên cứu về software design.

Inversion of Control in Relation to Frameworks

IoC có quan hệ với framework và code re-used. Thông thường khi sử dụng lại code chúng ta thường call một library của ai đó. Ví dụ trong .NET khi gọi method Math.Tan tức là make a call và tức là có control method đó (đơn là hãy nghĩ rằng sử dụng được nó có nghĩ là control được nó).
Nhưng khi thực hiện implement một IComparable hay IEnumerable thì .NET framework sẽ call ngược lại code implement. Trong những trường hợp này thì direction of control bị đảo ngược: something else calling you. Ví dụ implement IComparable thì phải implement method CompareTo. Khi chúng ta gọi hàm Sort thì .NET framework gọi ngược lại method CompareTo mà chúng ta implement.

Inversion of Control và Dependency Injection

Hai khái niệm này thường được coi là đồng nghĩa tuy nhiên DI chỉ là một dạng đặc biệt mô tả cách thực hiện IoC tức IoC có một phạm vi lớn hơn DI.

Inversion of Control và CAB

CAB là một framework IoC và cho phép chúng ta thực hiện DI. Tức CAB có thể thực hiện call us chứ không hoàn toàn là một framework để chúng ta call method và sử dụng. Ví dụ như trong lab về module loader hàm Load() của ModuleInit đã được CAB thực hiện.

Dependency Inversion

Một term có liên quan và dễ gây bối rối là Dependency Inversion. Dependency Inversion còn gọi là Dependency Inversion Principle- DIP, là wider concept của Dependency Injection. DI chỉ là một phần trong DIP, DIP quy định cách thức mà một high-module cần thực hiện khi sử dụng một low-module. Inversion (đảo ngược) ở đây nằm ở chỗ high level thông thường dựa trên low level thì sẽ chuyển lại giở đây cả high level và low level depend upon một shared abstraction. Software consultant Robert C. Martin (tham khảo Agile Software Development, Principles, Patterns, and Practices published by Prentice Hall 10/15/2002 ISBN-10: 0135974445) phát biểu như sau:

High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.

Đại khái là module cao hơn không nên phụ thuộc vào module bên dưới. Cả hai nên dựa vào một 'trừu tượng'. 'Trừu tượng' không được phụ thuộc vào 'chi tiết' mà 'chi tiết' sẽ phụ thuộc 'trừu tượng'.

DIP và IoC

Trong bài lab về DI chúng ta chỉ thực hiện invert dependent giữa các classes. Chúng ta chưa thấy IoC xuất hiện rõ ràng trong ví dụ đó. Nói chung chúng ta chưa cần đi quá sâu thay vì chỉ cần hiểu có thể làm được gì với CAB.

2010-01-17

Introduction to Composite Pattern

-->
Design patterns, CAB & SCSF

Hai phần trước đã nói sơ qua về CAB. Nhưng thật sự thì chưa có gì đọng lại ngoài những cái tên. Tiếp theo chúng ta sẽ điểm qua các Design patterns sử dụng trong CAB và SCSF. Các design patterns không thể liệt kê hết trong phần này mà cần tham khảo trong suốt những phần tiếp theo. Nếu một pattern được sử dụng trong CAB và SCSF cần tham khảo để tiếp tục thì mình sẽ bổ sung. Có thể tham khảo các design patterns tại http://www.dofactory.com/Patterns/Patterns.aspx
Giới thiệu Composite Pattern
 Đầu tiên sẽ đề cập đến design pattern cơ bản là Composite. Có thể tham khảo bài viết tại http://sourcemaking.com/design_patterns/composite.

Composite UML class diagram (sử dụng abstract class)

Composite UML class diagram (sử dụng interface)

Trong UML class diagram có thể thấy 3 phần chính
- Leaf là các đối tượng thành phần (hay còn gọi là Primitive).

- Component là giao diện cho các đối tượng thành phần, khai báo các method căn bản, là giao diện dùng khi access các thành phần.

- Composite định nghĩa các thao tác trên đối tượng thành phần, thực hiện lưu trữ và quản lý các đối tương thành phần.

Composite Pattern cho phép nhóm các object thành một single instance của một object. Các objects được nhóm có tính năng khá tương tự nhau. Object kết quả gọi là composite object. Việc thêm một component vào composite được hình dung tương tự việc thêm vào tree. Về kỹ thuật tất cả các Design patterns đều xoay quanh những tính năng của OOP encapsulation, inheritance, polymorphism...

Trong Composite kỹ thuật chính là polymorphism với 2 cách implement là polymorphism thông qua interface (recommended) và polymorphism qua abstract class.

Lab dành cho Composite Pattern

Ví dụ đơn giản khi có các region:
(England: (London: Chelsea)) và (France: Paris) nhóm thành Europe, một region lớn hơn như sau:

(Europe: (England: (London: Chelsea)) (France: Paris))

-->
Source code với C# (thực hiện qua interface)
Component.cs
-->

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Component interface
    /// </summary>
    interface Component
    {

        /// <summary>
        ///     Get the string of component (demo for component operation)
        /// </summary>
        ///
        ///     String of component
        /// </returns>
        string operation();

        /// <summary>
        ///     Get all children
        /// </summary>
        /// <returns>
        ///     List of <see cref="Component"/> children
        /// </returns>
        List<Component> getChildren();

        /// <summary>
        ///     Add to children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        void add(Component c);

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     A bool value...
        /// </returns>
        bool remove(Component c);
    }
}

Composite.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Composite
    /// </summary>
    class Composite : Component
    {

        /// <summary>
        ///     ID
        /// </summary>
        private string _id;

        /// <summary>
        ///     Children collection
        /// </summary>
        private List<Component> _components = new List<Component>();

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="id" type="string">
        ///    
        /// </param>
        public Composite(string id)
        {
            _id = id;
        }

        #region [ INTERFACE IMPLEMENTATION ]

        /// <summary>
        ///     Operation
        /// </summary>
        /// <returns>
        ///     A string value present name and list of children recursive
        /// </returns>
        public string operation()
        {
            string s = " (" + _id + ":";
            this.getChildren().ForEach
            (
                delegate(Component child)
                {
                    s += " " + child.operation();
                }
            );

            return s + ") ";
        }

        /// <summary>
        ///     Implement interface get all children
        /// </summary>
        /// <returns>
        ///     List of <see cref="Component"/> children
        /// </returns>
        public List<Component> getChildren()
        {
            return _components;
        }

        /// <summary>
        ///     Add to children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        public void add(Component c)
        {
            _components.Add(c);
        }

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     A bool value...
        /// </returns>
        public bool remove(Component c)
        {
            return _components.Remove(c);
        }

        #endregion

    }
}

Leaf.cs
-->

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Leaf
    /// </summary>
    class Leaf : Component
    {

        /// <summary>
        ///    
        /// </summary>
        private string _id;

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="id" type="string">
        ///     ID
        /// </param>
        public Leaf(string id)
        {
            _id = id;
        }

        #region [ INTERFACE IMPLEMENTATION ]

        /// <summary>
        ///    
        /// </summary>
        /// <returns>
        ///     A string value...
        /// </returns>
        public string operation()
        {
            return _id;
        }

        /// <summary>
        ///     Get all children
        /// </summary>
        /// <returns>
        ///     Just return null
        /// </returns>
        public List<Component> getChildren()
        {
            return null;
        }

        /// <summary>
        ///     Add to children collection, do nothing
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        public void add(Component c) { }

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     Just return false
        /// </returns>
        public bool remove(Component c) { return false; }

        #endregion

    }
}



Program.cs
-->
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Program
    /// </summary>
    class Program
    {

        /// <summary>
        ///     Main entry point
        /// </summary>
        /// <param name="args" type="string[]">
        ///    
        /// </param>
        static void Main(string[] args)
        {

            // England
            Composite england = new Composite("England");

            // London
            Composite london = new Composite("London");
            london.add(new Leaf("Chelsea"));
            england.add(london);

            // Manchester
            Leaf manchester = new Leaf("Manchester");
            england.add(manchester);
            england.remove(manchester);

            // France
            Composite france = new Composite("France");
            france.add(new Leaf("Paris"));

            // Europe
            Composite europe = new Composite("Europe");
            europe.add(england);
            europe.add(france);

            // Get Europe
            Console.WriteLine(europe.operation());
            Console.ReadKey();
        }
    }
}

Source code với C# (thực hiện qua abstract class)
Component.cs
-->

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Component interface
    /// </summary>
    public abstract class Component
    {

        /// <summary>
        ///     ID
        /// </summary>
        protected string _id;

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="id" type="string">
        ///    
        /// </param>
        public Component(string id)
        {
            _id = id;
        }

        /// <summary>
        ///     Get all children
        /// </summary>
        /// <returns>
        ///     List of <see cref="Component"/> children
        /// </returns>
        public abstract List<Component> getChildren();

        /// <summary>
        ///     Get the string of component (demo for component operation)
        /// </summary>
        /// <returns>
        ///     String of component
        /// </returns>
        public abstract string operation();

        /// <summary>
        ///     Add to children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        public abstract void add(Component c);

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     A bool value...
        /// </returns>
        public abstract bool remove(Component c);
    }
}


Composite.cs
-->
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns
{

    /// <summary>
    ///     Composite
    /// </summary>
    class Composite : Component
    {

        /// <summary>
        ///     Children collection
        /// </summary>
        private List<Component> _components = new List<Component>();

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="id" type="string">
        ///    
        /// </param>
        public Composite(string id)
            : base(id)
        { }

        #region [ OVERRIDE METHODS ]

        /// <summary>
        ///     Operation
        /// </summary>
        /// <returns>
        ///     A string value present name and list of children recursive
        /// </returns>
        public override string operation()
        {
            string s = " (" + _id + ":";
            this.getChildren().ForEach(delegate(Component child) { s += " " + child.operation(); });
            return s + ") ";
        }

        /// <summary>
        ///     Implement interface get all children
        /// </summary>
        /// <returns>
        ///     List of <see cref="Component"/> children
        /// </returns>
        public override List<Component> getChildren()
        {
            return _components;
        }

        /// <summary>
        ///     Add to children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        public override void add(Component c)
        {
            _components.Add(c);
        }

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     A bool value...
        /// </returns>
        public override bool remove(Component c)
        {
            return _components.Remove(c);
        }

        #endregion

    }
}

Leaf.cs
-->
using System;
using System.Collections.Generic;
using System.Text;


namespace DesignPatterns
{

    /// <summary>
    ///     Leaf
    /// </summary>
    class Leaf : Component
    {

        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="id" type="string">
        ///     ID
        /// </param>
        public Leaf(string id) : base(id) { }

        #region [ OVERRIDE METHODS ]

        /// <summary>
        ///    
        /// </summary>
        /// <returns>
        ///     A string value...
        /// </returns>
        public override string operation()
        {
            return _id;
        }

        /// <summary>
        ///     Get all children
        /// </summary>
        /// <returns>
        ///     Just return null
        /// </returns>
        public override List<Component> getChildren()
        {
            return null;
        }

        /// <summary>
        ///     Add to children collection, do nothing
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to add
        /// </param>
        public override void add(Component c) { }

        /// <summary>
        ///     Remove from children collection
        /// </summary>
        /// <param name="c" type="Component">
        ///     Child <see cref="Component"/> to remove
        /// </param>
        /// <returns>
        ///     Just return false
        /// </returns>
        public override bool remove(Component c) { return false; }

        #endregion

    }
}

Qua bài này chúng ta sẽ chính thức tìm hiểu CAB. Part tiếp theo sẽ là part đầu tiên và mình sẽ đánh số cho dễ theo dõi bắt đầu là Part 1.