设计模式-装饰模式(Decorator)

一、装饰模式(Decorator)

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

二、装饰模式UML图

(1)Component:定义了一个对象接口,可以给这些对象动态的添加职责

(2)ConcreteComponent:定义了一个具体的对象,可以给这个对象添加一些职责

(3)Decorator:装饰抽象类,集成了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的

(4)ConcreteDecoratorA、ConcreteDecoratorB:具体的装饰对象,起到给Component添加职责的功能

三、代码实现

Component类

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

ConcreteComponent类

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

Decorator类

abstract class Decorator : Component
    {
        protected Component component;

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

        public override void Operation()    //重写Operation(),实际执行的是Component的Operation()
        {
            if (component !=null )
            {
                component.Operation();
            }
        }
    }

ConcreteDecorator类

class ConcreteDecoratorA :Decorator
    {
        private string addedState;  //本类独有的功能,以区别于ConcreteDecoratorB

        public override void Operation()
        {
            base.Operation();   //首先运行原Component的Operation(),再执行本类的功能,如addedState(),相当于对原Copmponent进行了装饰
            addedState = "New State";
            Console.WriteLine("具体装饰对象A的操作");
        }
    }


class ConcreteDecoratorB : Decorator
    {
        public override void Operation()
        {
            base.Operation();   //首先运行原Component的Operation(),再执行本类的功能,如AddedBehavior(),相当于对原Copmponent进行了装饰
            AddedBehavior();
            Console.WriteLine("具体装饰对象B的操作");
        }

        private void AddedBehavior()    //本类独有的方法,以区别ConcreteDecoratorA
        {

        }
    }

客户端代码

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

            //装饰的方法是:首先用ConcreteComponent实例化对象c
            //             然后用ConcreteDecoratorA的实例化对象d1来包装c,
            //             再用ConcreteDecoratorB的对象d2来包装d1,
            //             最终执行d2的Operation()
            d1.SetComponent(c);                        
            d2.SetComponent(d1);
            d2.Operation();

            Console.Read();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值