装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

介绍

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

主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

何时使用:在不想增加很多子类的情况下扩展类。

如何解决:将具体功能职责划分,同时继承装饰者模式。

关键代码: 1、Component 类充当抽象角色,不应该具体实现。 2、修饰类引用和继承 Component 类,具体扩展类重写父类方法。

应用实例: 1、孙悟空有 72 变,当他变成"庙宇"后,他的根本还是一只猴子,但是他又有了庙宇的功能。 2、不论一幅画有没有画框都可以挂在墙上,但是通常都是有画框的,并且实际上是画框被挂在墙上。在挂在墙上之前,画可以被蒙上玻璃,装到框子里;这时画、玻璃和画框形成了一个物体。

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

缺点:多层装饰比较复杂。

使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。

注意事项:可代替继承。

实现

我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。然后我们创建一个实现了 Shape 接口的抽象装饰类 ShapeDecorator,并把 Shape 对象作为它的实例变量。

RedShapeDecorator 是实现了 ShapeDecorator 的实体类。

DecoratorPatternDemo,我们的演示类使用 RedShapeDecorator 来装饰 Shape 对象。

装饰器模式的 UML 图

步骤 1

创建一个接口。

Shape.cs

namespace Decorator_Pattern
{
    interface Shape
    {
        void draw();
    }
}

步骤 2

创建实现接口的实体类。

Rectangle.cs

using System;
namespace Decorator_Pattern
{
    class Rectangle : Shape
    {
        public void draw()
        {
            Console.WriteLine("Shape: Rectangle");
        }
    }
}

Circle.cs

using System;
namespace Decorator_Pattern
{
    class Circle : Shape
    {
        public void draw()
        {
            Console.WriteLine("Shape: Circle");
        }
    }
}

步骤 3

创建实现了 Shape 接口的抽象装饰类。

ShapeDecorator.cs

namespace Decorator_Pattern
{
    //装饰类
    abstract class ShapeDecorator : Shape
    {
        protected Shape decoratedShape;
        public ShapeDecorator(Shape decoratedShape)
        {
            this.decoratedShape = decoratedShape;
        }

        public abstract void draw();
     
    }
}

步骤 4

创建扩展了 ShapeDecorator 类的实体装饰类。

RedShapeDecorator.cs

using System;
namespace Decorator_Pattern
{
    class RedShapeDecorator : ShapeDecorator
    {
        public RedShapeDecorator(Shape decoratedShape)
            : base(decoratedShape)
        {

        }

        public override void draw()
        {
            decoratedShape.draw();
            SetRedBorder(decoratedShape);  //给Shape拓展红框的功能
        }

        void SetRedBorder(Shape decoratedShape)
        {
            Console.WriteLine("Border Color: Red");
        }
    }
}

步骤 5

使用 RedShapeDecorator 来装饰 Shape 对象。

DecoratorPatternDemo.cs

using System;
namespace Decorator_Pattern
{
    class DecoratorPatternDemo 
    {
        static void Main(string[] args)
        {
            Shape circle = new Circle();
            Shape redCircle = new RedShapeDecorator(new Circle());
            Shape redRectangle = new RedShapeDecorator(new Rectangle());

            Console.WriteLine("\nCircle with normal border");
            circle.draw();

            Console.WriteLine("\nCircle of red border");
            redCircle.draw();

            Console.WriteLine("\nRectangle of red border");
            redRectangle.draw();

            Console.Read();
        }
    }
}

步骤 6

验证输出。

Circle with normal border
Shape: Circle

Circle of red border
Shape: Circle
Border Color: Red

Rectangle of red border
Shape: Rectangle
Border Color: Red


拓展例子

装饰模式有很多应用,例如装饰模式为已有类动态附加额外的功能就像LOL、王者荣耀等类Dota游戏中,英雄升级一样。每次英雄升级都会附加一个额外技能点学习技能。具体的英雄就是ConcreteComponent,技能栏就是装饰器Decorator,每个技能就是ConcreteDecorator;

using System;
namespace LearnSkill
{
    //Component英雄接口
    public interface Hero
    {
        //学习技能
        void learnSkills();
    }

    //ConcreteComponent 具体英雄坦克职业
    public class Tank : Hero
    {
        string name;

        public Tank(string name)
        {
            this.name = name;
        }

        public void learnSkills()
        {
            Console.WriteLine(name + "学习了以上技能!");
        }
    }

    //Decorator 技能栏
    public class Skills : Hero
    {
        Hero hero;

        public Skills(Hero hero)
        {
            this.hero = hero;
        }

        public virtual void learnSkills()
        {
            if (hero != null)
                hero.learnSkills();
        }
    }

    //ConcretDecrator 技能: Q
    public class Skill_Q : Skills
    {
        string skillName;

        public Skill_Q(Hero hero, string skillName)
            : base(hero)
        {
            this.skillName = skillName;
        }

        public override void learnSkills()
        {
            Console.WriteLine("学习了技能Q:" + skillName);
            base.learnSkills();
        }
    }

    public class Skill_W : Skills
    {
        string skillName;

        public Skill_W(Hero hero, string skillName)
            : base(hero)
        {
            this.skillName = skillName;
        }

        public override void learnSkills()
        {
            Console.WriteLine("学习了技能W:" + skillName);
            base.learnSkills();
        }
    }

    //ConcretDecorator 技能:E
    public class Skill_E : Skills
    {
        string skillName;

        public Skill_E(Hero hero, string skillName)
            :base(hero)
        {
            this.skillName = skillName;
        }

        public override void learnSkills()
        {
            Console.WriteLine("学习了技能E:" + skillName);
            base.learnSkills();
        }
    }

    //ConcretDecorator 技能:R
    public class Skill_R : Skills
    {
        string skillName;

        public Skill_R(Hero hero, string skillName)
            : base(hero)
        {
            this.skillName = skillName;
        }

        public override void learnSkills()
        {
            Console.WriteLine("学习了技能R:" + skillName);
            base.learnSkills();
        }
    }

    class Player
    {
        static void Main(string[] args)
        {
            Hero hero = new Tank("亚瑟");
            Skills skills = new Skills(hero);
            Skills r = new Skill_R(skills, "圣剑裁决");
            Skills e = new Skill_E(r, "回旋打击");
            Skills w = new Skill_W(e, "誓约之盾");
            Skills q = new Skill_Q(w, "圣光守护");
            //学习技能
            q.learnSkills();
            Console.Read();
        }
    }
}
输出:

学习了技能Q: 圣光守护
学习了技能W: 誓约之盾
学习了技能E: 回旋打击
学习了技能R: 圣剑裁决
亚瑟学习了以上技能!