Net设计模式实例之装饰者模式(Decorator Pattern)

一、装饰模式简介(Brief Introduction

动态地给一个对象添加一些额外的职责。

优点:把类中的装饰功能从类中搬移出去,这样可以简化原有的类。有效地把类的核心功能和装饰功能区分开了。

 

二、解决的问题(What To Solve

已经开发完毕的对象,后期由于业务需要,对旧的对象需要扩展特别多的功能,这时候使用给对象动态地添加新的状态或者行为(即装饰模式)方法,而不是使用子类静态继承。

比如,刚买一辆汽车如下图

此汽车不符合你的个性要求,比如外表不够美观,发动机马力不足,不能满足你的速度激情,于是你需要对汽车的外表进行装饰,同时需要提高发动机的性能。这些操作通过装饰模式就能很好地解决问题。最终得到如下图所示的个性汽车。

三、装饰模式分析(Analysis

1、装饰模式结构

Component定义了一个对象接口,可以给这些对象动态地添加职责。

ComcreteComponent定了一个具体的对象,也可以给这个具体的对象添加职责。

Decorator抽象装饰类,继承了Component对象接口,从外类扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在。

ConcreteDecoratorA具体的装饰对象,起到给Component添加职责的功能。

ConcreteDecoratorB具体的装饰对象,起到给Component添加职责的功能。

2、源代码

1、对象接口Component.cs

public abstract class Component

{

    public abstract void Operation();

}

 

2、实现类ConcreteComponent.cs 继承于Component接口

public class ConcreteComponent : Component

{

    public override void Operation()

    {

        Console.WriteLine("开始执行具体的对象...");

    }

}

 

3、装饰抽象类Decorator.cs 继承于Component接口

public abstract class Decorator : Component

{

    private Component m_Component;

 

    public void SetComponent(Component component)

    {

        this.m_Component = component;

    }

 

    public override void Operation()

    {

        if (m_Component != null)

       {

            m_Component.Operation();

       }

    }

}

 

4、具体的装饰对象ConcreteDecoratorA.cs 继承于Decorator抽象类

public class ConcreteDecoratorA : Decorator

{

    private string addedState;

    public override void Operation()

    {

        base.Operation();

        addedState = "进行了状态属性装饰。";

        Console.WriteLine(addedState);

    }

}

给对象接口Component添加了状态属性addedState

 

5、具体的装饰对象ConcreteDecoratorB.cs 继承于Decorator抽象类

public class ConcreteDecoratorB : Decorator

{

    public override void Operation()

    {

        base.Operation();

        AddedBehavior();

    }

 

    private void AddedBehavior()

    {

        Console.WriteLine("进行了操作行为装饰。");

    }

}

 

 

给对象接口Component添加了操作行为AddedBehavior()

 

5、客户端代码

static void Main(string[] args)

{

    ConcreteComponent cc = new ConcreteComponent();

    ConcreteDecoratorA cda = new ConcreteDecoratorA();

    ConcreteDecoratorB cdb = new ConcreteDecoratorB();

 

    cda.SetComponent(cc);

    cdb.SetComponent(cda);

    cdb.Operation();

    Console.Read();

}

给对象接口Component添加了操作行为AddedBehavior()

3、程序运行结果

四.案例分析(Example

此案例对具体组件TextView进行了BorderScrollBar的装饰。使TextView更符合项目需求。

五、总结(Summary

装饰模式,给一个对象动态添加额外职责,这些职责需要由用户决定加入的方式和时机。装饰模式提供了“即插即用”的方式,在运行期间决定何时增加何种功能。就增加功能来说,装饰模式比生成子类更加灵活。
posted @ 2010-01-19 09:14  灵动生活  阅读(3654)  评论(7编辑  收藏  举报