装饰模式

装饰模式:动态的给一个对象添加额外的职责,就增加功能来说,Decorator模式比生成子类更为灵活。。

Decorator模式的工作原理是:可以创建始于Decorator对象(负责新的功能的对象)终于原对象的一个对象“链”。

ConcreteComponent让Decorator对象为自己添加功能。有时候使用ConcreteComponent的派生类提供核心功能,在这种情况就是用ConcreteComponent替代了Component的功能,而且装饰者是继承于ConcreteComponent的子类。

Component定义ConcreteComponent和Decorator类要实现的方法,简单来说如果一个类继承于该类就具有装饰或被装饰能力。 

Decorator具有特定装饰功能的类,用来装饰ConcreteComponent类。

代码如下:

Component类

abstract class Component
{
    public abstract void Operation();
}

ConcreteComponent类

class ConcreteComponent : Component
{
    public override void Operation()
    {
        Console.WriteLine("具体对象的操作");
    }
}

Decorate类

abstract class Decorate : Component
{
    protected Component component;
    public void SetComponent(Component component)
    {
        this.component = component;
    }
    public override void Operation()
    {
        if (component != null)
            component.Operation();
    }

}

ConcreteDecoratorA类

class ConcreteDecoratorA : Decorate
{
    public string addedState;//A类独有的功能
    public override void Operation()
    {
        base.Operation();
        addedState = "New State";
        Console.WriteLine("具体装饰对象A的操作"+ addedState);
    }
}

ConcreteDecoratorB类

class ConcreteDecoratorB : Decorate
{
    public override void Operation()
    {
        base.Operation();
        AddedBehavior();  //B类独有的方法
        Console.WriteLine("具体装饰对象B的操作");
    }

    private void AddedBehavior()
    {
        Console.WriteLine("B类独有/添加的方法");
    }
}

调用:

static void Main(string[] args)
{
    ConcreteComponent c = new ConcreteComponent();
    ConcreteDecoratorA d1 = new ConcreteDecoratorA();
    ConcreteDecoratorB d2 = new ConcreteDecoratorB();

    
     d1.SetComponent(c);
     d2.SetComponent(d1);
     d2.Operation();

  
    Console.ReadKey();
}

运行结果:

 参考文章:

http://www.cnblogs.com/rush/archive/2011/05/08/Decorator_DesignPattern_NETFramework.html

原文地址:https://www.cnblogs.com/sunice/p/6686922.html