Thứ Hai, 23 tháng 7, 2012

Design Pattern - Decorator

1. Đặt vấn đề
Khi xây dựng một ứng dụng, một thời gian nào đó chúng ta muốn mở rộng và thay đổi ứng dụng cho phù hợp với nhu cầu thực tế nhưng vấn đề này sẽ mất rất nhiều thời gian hơn là việc phát triển một ứng dụng mới hoàn toàn.
 Do đó trước khi xây dựng một ứng dụng chúng ta phải thiết kế ứng dụng làm sao để thuận lợi cho việc mở rộng ứng dụng, mẫu Decorator sẽ giúp chúng ta giải quyết được vấn đề này.
2.Ý nghĩa
 Mẫu decorator cung cấp phương pháp mềm dẻo cho phép các lớp con mở rộng các chức năng.
3. UML

participants

    The classes and/or objects participating in this pattern are:
  • Component   (LibraryItem)
    • defines the interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent   (Book, Video)
    • defines an object to which additional responsibilities can be attached.
  • Decorator   (Decorator)
    • maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • ConcreteDecorator   (Borrowable)
    • adds responsibilities to the component.
4. Code demo
  class ConcreteComponent : Component
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteComponent:Component");
        }
    }

    abstract class Decorator
    {
        Component _component;
        public Decorator(Component component)
        {
            this._component = component;
        }
        public void Operation()
        {
            if (_component != null)
            {
                _component.Operation();
            }
        }
    }
    class ConcreteDecoratorA:Decorator
    {
        public void Operation()
        {
            base.Operation();
            Console.WriteLine("ConcreteDecoratorA");
        }
    }
    class ConreteDecoratorB : Decorator
    {
        public void Operation()
        {
            base.Operation();
            Console.WriteLine("ConcreteDecoratorB");
        }
    }

 

Không có nhận xét nào:

Đăng nhận xét