zoukankan      html  css  js  c++  java
  • 七.装饰模式

    装饰模式:

           为已有功能动态的添加更多的功能。

           如果没有抽象实体,装饰类直接继承实体。

           如果只有一个装饰实体,可以将装饰实体与抽象装饰类合并。???

    装饰类:

           //装饰类

       abstract class Decorator : Component

        {

           protected Component component;

           public void SetComponent(Component component)

           {

               this.component = component;

           }

           public override void Operation()

           {

               if (component != null)

               {

                    component.Operation();

               }

           }

    }

    装饰实体

               //实体

       class ConcreteDecoratorA : Decorator

        {

           private string addedState;

           public override void Operation()

           {

               //运行基类的Operation方法,再执行本类功能

               //相当于对原类Component进行了装饰

               base.Operation();

               addedState = "New State";

               Console.WriteLine("具体装饰对象A的操作");

           }

        }

       class ConcreteDecoratorB : Decorator

        {

           public override void Operation()

           {

               base.Operation();

               AddedBehavior();

               Console.WriteLine("具体装饰对象B的操作");

           }

           public void AddedBehavior()

           {

               //本类独有的方法

               Console.WriteLine("B独有的方法");

           }

        }

    装饰类所装饰的实体:

           //抽象类,Component(组成,部件元件)

       abstract class Component

        {

           //(操作)

           public abstract void Operation();

        }

       //实体

       class ConcreteComponent : Component

        {

           public override void Operation()

           {

               Console.WriteLine("具体对象的操作");

           }

    }

    使用:

                         ConcreteComponentc = new ConcreteComponent();

               ConcreteDecoratorA d1 = new ConcreteDecoratorA();

               ConcreteDecoratorB d2 = new ConcreteDecoratorB();

               d1.Operation();

               d2.Operation();

               Console.WriteLine();

               d1.SetComponent(d2);

               d1.Operation();

  • 相关阅读:
    UVA 12545 Bits Equalizer
    UVA 1610 Party Games
    UVA 1149 Bin Packing
    UVA 1607 Gates
    UVA 12627 Erratic Expansion
    UVA10562-Undraw the Trees(递归)
    UVA10129-Play on Words(欧拉路径)
    UVA816-Abbott's Revenge(搜索进阶)
    UVA1103-Ancient Messages(脑洞+dfs)
    UVA839-Not so Mobile
  • 原文地址:https://www.cnblogs.com/yaoge/p/1815227.html
Copyright © 2011-2022 走看看