装饰者模式

Component定义一个对象接口,可以给对象动态地添加职责。ConcreteComponent定义一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,无需知道Decorator的存在,至于ConcreteDecorator是具体的装饰对象,起到给Component添加职责的功能。

代码:

/// <summary>
    /// 装饰行为的抽象
    /// </summary>
    public abstract class Component
    {
        //操作
        public abstract void Operation();
    }

    /// <summary>
    /// 被装饰的对象
    /// </summary>
    public class ConcreteComponent : Component
    {
        public override void Operation()
        {
            Console.WriteLine("具体对象的操作");
        }
    }

    /// <summary>
    /// 抽象的装饰类
    /// </summary>
    public abstract class Decorator : Component
    {
        protected Component component;

        public void SetComponent(Component component)
        {
            this.component = component;
        }

        public override void Operation()
        {
            if (component != null)
            {
                component.Operation();
            }
        }
    }

    /// <summary>
    /// 具体的装饰类
    /// </summary>
    public class ConcreteDecoratorA : Decorator
    {
        private void AddedBehaviorA()
        {
            Console.WriteLine("装饰A");
        }

        public override void Operation()
        {
            base.Operation();
            AddedBehaviorA();
        }
    }

    public class ConcreteDecoratorB : Decorator
    {
        private void AddedBehaviorB()
        {
            Console.WriteLine("装饰B");
        }

        public override void Operation()
        {
            base.Operation();
            AddedBehaviorB();
        }
    }

调用:

        static void Main(string[] args)
        {
            //定义被装饰对象 主装饰对象
            ConcreteComponent cc = new ConcreteComponent();
            //定义具体装饰对象A 主对象上的装饰
            ConcreteDecoratorA cda = new ConcreteDecoratorA();
            //定义具体装饰对象A 主对象上的装饰
            ConcreteDecoratorB cdb = new ConcreteDecoratorB();

            //装饰对象A 装扮主对象cc
            cda.SetComponent(cc);
            //装饰对象B 装扮装饰对象A
            cdb.SetComponent(cda);
            //开始装扮
            cdb.Operation();

            //第二种装扮
            //装饰对象B 装扮主对象cc
            cdb.SetComponent(cc);
            //装饰对象A 装扮装饰对象B
            cda.SetComponent(cdb);
            //开始装扮
            cda.Operation();
      }

输出:

原文地址:https://www.cnblogs.com/nygfcn1234/p/3392401.html