当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 装饰器模式

设计模式系列 - 装饰器模式

2018年12月25日  | 移动技术网IT编程  | 我要评论

装饰器模式允许向现有对象中添加新功能,同时又不改变其结构。

介绍

装饰器模式属于结构型模式,主要功能是能够动态地为一个对象添加额外功能。在保证现有功能的基础上,再添加新功能,可联想到 wpf 中的附件属性。

类图描述

由上图可知,我们定义了一个基础接口 ishape 用于约定对象的基础行为。然后通过定义shapedecorator 类 来扩展功能,redshapledecorator 为具体的扩展实现。

代码实现

1、定义接口

public interface ishape
{
    void draw();
}

2、定义对象类型

public class circle:ishape
{
    public void draw()
    {
        console.writeline("shape:circle");
    }
}

public class rectangle : ishape
{
    public void draw()
    {
        console.writeline("shape:rectangle");
    }
}

3、定义新的扩展装饰类

public class shapedecorator:ishape
{
    protected ishape decoratedshape;

    public shapedecorator(ishape decoratedshape)
    {
        this.decoratedshape = decoratedshape;
    }

    public virtual void draw()
    {
        decoratedshape.draw();
    }
}

4、定义扩展类的具体实现

public class redshapledecorator : shapedecorator
{
    public redshapledecorator(ishape decoratedshape) : base(decoratedshape)
    {
    }

    public override void draw()
    {
        this.decoratedshape.draw();
        setredborder(this.decoratedshape);
    }

    private void setredborder(ishape decoratedshape)
    {
        console.writeline("border color:red");
    }
}

5、上层调用

class program
{
    static void main(string[] args)
    {
        ishape circle = new circle();
        ishape redcircle = new redshapledecorator(new circle());

        ishape redrectangle = new redshapledecorator(new rectangle());
        console.writeline("circle with normal border");
        circle.draw();

        console.writeline("circle of red border");
        redcircle.draw();

        console.writeline("rectangel of red border");
        redrectangle.draw();

        console.readkey();
    }
}

总结

装饰器模式使得对象的核心功能和扩展功能能够各自独立扩展互不影响。但是对于装饰功能较多的情况下不建议采用这种模式。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网