美文网首页
( Design Patterns ) Structural D

( Design Patterns ) Structural D

作者: 乔什华 | 来源:发表于2016-10-01 14:50 被阅读0次

    Definition

    Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

    Components

    1. ComponentBase: base class for all concrete components and decorators.
    2. ConcreteComponent: inherits from ComponentBase. Concrete component classes that may be wrapped by the decorators.
    3. DecoratorBase: base class for decorators. It has a constructor that accepts a ComponentsBase as its parameters.
    4. ConcreteDecorator: It may include some additional methods which extend the functionality of components.
    Decorator pattern umlDecorator pattern uml

    Sample code

    static class Program
    {
        static void Main()
        {
            var component = new ConcreteComponent();
            var decorator = new ConcreteDecorator(component);
            decorator.Operation();
        }
    }
    
    public abstract class ComponentBase
    {
        public abstract void Operation();
    }
    
    class ConcreteComponent : ComponentBase
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteComponent.Operation()");
        }
    }
    
    public abstract class DecoratorBase : ComponentBase
    {
        private readonly ComponentBase _component;
    
        protected DecoratorBase(ComponentBase component)
        {
            _component = component;
        }
    
        public override void Operation()
        {
            _component.Operation();
        }
    }
    
    public class ConcreteDecorator : DecoratorBase
    {
        public ConcreteDecorator(ComponentBase component) : base(component) { }
    
        public override void Operation()
        {
            base.Operation();
            Console.WriteLine("[ADDITIONAL CODE BLOCK]");
        }
    }
    

    Advantages

    1. It helps to achieve extending the components' functionality by avoiding changing components' original logic.
    2. It provides a flexible alternative to subclassing for extending functionality, which could change components' behavior at runtime.

    Reference

    Design Patterns 2 of 3 - Structural Design Patterns - CodeProject
    Head First Design Patterns - O'Reilly Media

    相关文章

      网友评论

          本文标题:( Design Patterns ) Structural D

          本文链接:https://www.haomeiwen.com/subject/ycbryttx.html