c#设计模式——装饰模式

一 概要

1.1 结构型模式

  1. 关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。

1.2 定义

  1. 指在不改变现有对象结构的情况下,动态地给该对象增加一些额外的职责。

二 UML类图

在这里插入图片描述

三 例子

 	public interface Component
    {
        void Operation();
    }

    public class ConcreteComponent : Component
    {
        public void Operation()
        {
            //todo
        }
    }

    public abstract class Decorator : Component
    {
        private Component component;

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

        public virtual void Operation()
        {
            if (this.component != null)
            {
                this.component.Operation();
            }
        }
    }

    public class DecoratorA : Decorator
    {
        private string state;
        public override void Operation()
        {
            base.Operation();
            //todo
            state = "todo";
        }
    }

    public class DecoratorB : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            //todo
            Other();
        }

        private void Other()
        {

        }
    }
    
	 public Test()
     {
          ConcreteComponent concreteComponent = new ConcreteComponent();
          DecoratorA decoratorA = new DecoratorA();
          DecoratorB decoratorB = new DecoratorB();
          decoratorA.SetComponent(concreteComponent);
          decoratorB.SetComponent(decoratorA);
          decoratorB.Operation();
      }

四 优缺点

4.1 优点

  1. 把类中的装饰功能从类中搬移去除,简化了原有的类。
  2. 有效地把类的核心职责和装饰功能区分开来,而且可以去除相关类中重复的装饰逻辑。
  3. 比继承更加灵活机动。

4.2 缺点

  1. 这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。
  2. 装饰模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。

五 使用场景

  1. 装饰模式是为已有功能动态地添加更多功能的一种方式。当系统需要新功能, 而向旧的类中添加新的代码是为了装饰原有类的核心职责或主要行为时,而且向旧的类中添加新的方法和逻辑只会在某些特定的情况下才会用到, 这个时候就可以使用装饰模式, 把装饰的代码放在单独的类中,并让这个类包装它需要装饰的对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值