您的位置:首页 > 编程语言 > C#

[用设计模式锻炼C#系列]之Decorator

2003-05-09 12:12 525 查看
名称:Decorator
中文名称:装饰
类型:结构型
简介:我想当你真正的理解此模式时,
你可能会像侯sir那样,击节而歌.
暗叹精妙.好潇洒的连环.当然这里的
精妙主要在语言的实现上.
一般此模式,用于动态的给一个对象添加
职责.向其它很多模式一样,替代"纯粹"的
继承对象体系的设计.注意这里强调"纯粹"
也可说成是"静态".因为decorator的实现
很依赖继承的特性.但它对于职责的添加是
动态的,而不是通过预先设计大量的要求对
象,以便需求.它架构对象系统的指导理念
是通过小对象逐步"叠加"("作用")构成最终
需求的大对象.
[C#]
声明:这里由于重在C#的锻炼.所以事例中不采用
涉及连环调用,紧以简单类示:

// created on 2003-3-18 at 20:
//Environment Tool : sharpdevelop ....
// Member object : component concretecomponent decorator condecorator

using System;

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

class ConcreteComponent : Component
{
private string m_STR;
public ConcreteComponent(string m_STRinparam)
{
m_STR = m_STRinparam;
}

public override void Draw()
{
Console.WriteLine
("I am concretecomponent......./n{0} ", m_STR);
}
}

class Decorator : Component
{
protected Component decoratoredobject;

public void SetComponent(Component m_OBJinparam)
{
decoratoredobject = m_OBJinparam ;
}
public override void Draw()
{
if (decoratoredobject != null)
decoratoredobject.Draw();
}
}

class ConcreteDecorator : Decorator
{
private string strDecoratorName;
public ConcreteDecorator (string m_STRinparam)
{
strDecoratorName = m_STRinparam;
}
public override void Draw()
{
CustomDecoration();
base.Draw();
}
void CustomDecoration()
{
Console.WriteLine("In concretedecorator..........");
Console.WriteLine("{0}", strDecoratorName);
}
}

public class DesignPattern_Decorator_Test
{
public static void Main(string[] args)
{
ConcreteComponent m_DECobj1 =
new ConcreteComponent("I am the component which will be decorated......../n");

ConcreteDecorator m_DECobj2 =
new ConcreteDecorator("I will decorate the component..........");

m_DECobj2.SetComponent(m_DECobj1);

Component result = m_DECobj2;
result.Draw();
}
}

点评:1.这里的abstract也是C#对抽象类的原生支持.
这里是不可使用interface的,因为需要"多重"的重载.
2.在concretedecorator单一的情况下可以将decorator并入concretedecorator.
2.小对象逐步构件大对象,很多情况下,适宜采用strategy.
譬如component定义的接口太臃肿,那么concretedecorator的
负担会太重.而采用小对象strategy,逐步实现大对象,负担
不会很重,而且strategy的优点亦可产生作用:通过小对象接口
实现decorator多样化.

---------------------------------------------------------------------
声明:本程式重在演示C#基本用法
不考虑在实际环境中应用带来
其它问题的情况.
如:多线程.
系列文章声明请见第一篇:
[用设计模式锻炼C#基本功系列]之Singleton、Bridge
---------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: