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

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

    namespace Decorator
    {
        public abstract class Component
        {
            public abstract void Operation();
        }
        public class ConcreteComponent:Component
        {
            public override void Operation()
            {
                Console.WriteLine("具体对象的操作");
            }
        }
        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();
                }
            }
        }
        public class ConcreteDecoratorA:Decorator
        {
            private string addedState;
            public override void Operation()
            {
                base.Operation();
                addedState = "New State";
                Console.WriteLine("具体装饰对象A的操作");
            }
        }
        public class ConcreteDecoratorB : Decorator
        {
            public override void Operation()
            {
                base.Operation();
                AddedBehavior();
                Console.WriteLine("具体装饰对象B的操作");
            }
            private void AddedBehavior()
            {
    
            }
        }
    }
    View Code

    测试代码:

                ConcreteComponent c = new ConcreteComponent();
                ConcreteDecoratorA d1 = new ConcreteDecoratorA();
                ConcreteDecoratorB d2 = new ConcreteDecoratorB();
                d1.SetComponent(c);
                d2.SetComponent(d1);
                d2.Operation();
  • 相关阅读:
    安装hp驱动
    原来这才是真的卑躬屈膝
    vim好文集锦
    解决python交互时无法使用回格键
    难道父母比希望你快乐吗?
    从C 语言用户角度理解 Linux 的库
    树梅派屏幕旋转方法
    如此瘸了
    一首难忘的歌
    将安卓手机屏幕投射到 Linux
  • 原文地址:https://www.cnblogs.com/uptothesky/p/5253118.html
Copyright © 2011-2022 走看看