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

    装饰模式:动态的给一个对象添加额外的职责,就增加功能来说,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

  • 相关阅读:
    高斯消元学习
    HDU 4596 Yet another end of the world(解一阶不定方程)
    Codeforces Round #318 div2
    HDU 4463 Outlets(一条边固定的最小生成树)
    HDU 4458 Shoot the Airplane(计算几何 判断点是否在n边形内)
    HDU 4112 Break the Chocolate(简单的数学推导)
    HDU 4111 Alice and Bob (博弈)
    POJ 2481 Cows(线段树单点更新)
    HDU 4288 Coder(STL水过)
    zoj 2563 Long Dominoes
  • 原文地址:https://www.cnblogs.com/sunice/p/6686922.html
Copyright © 2011-2022 走看看