代码改变世界

设计模式之装饰模式(Decorator)

2010-01-15 22:27  key_sky  阅读(196)  评论(0编辑  收藏  举报

装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。Component是定义了一个对象接口,可以给这些对象动态
地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
优点:有效地把类的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑如果只有一个ConcreteCompent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以吧Decorator和ConcreteDecorator的责任合并成一个类。

Component.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;

//装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式
//比生成子类更为灵活。Component是定义了一个对象接口,可以给这些对象动态
//地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象
//添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Com
//ponent类的功能,但对于Component来说,是无需知道Decorator的存在。至于
//ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
//优点:有效地把类的装饰功能从类中搬移去除,这样可以简化原有的类,有效地
//把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑

//如果只有一个ConcreteCompent类而没有抽象的Component类,那么Decorator类可
//以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorat
//or类,那么就没有必要建立一个单独的Decorator类,而可以吧Decorator和Concr
//eteDecorator的责任合并成一个类
namespace DecoratorPattern
{
class Coponent2
{
}
//Component类
abstract class Component
{
public abstract void Operation();
}

//ConcreteComponent类
class ConcreteComponet : Component
{
public override void Operation()
{
Console.WriteLine(
"具体对象的操作");
}
}

//Decorator类
abstract class Decorator : Component
{
protected Component component;

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

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

//ConcreteDecoratorA
class ConcreteDecoratorA : Decorator
{
private string addedState;

public override void Operation()
{
base.Operation();//运行基类,并装饰新功能
addedState = "New State";
Console.WriteLine(
"具体装饰对象A的操作" + addedState);
}
}

class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine(
"具体装饰对象B的操作");
}

private void AddedBehavior()
{

}
}
}

Program.cs:

代码
using System;
using System.Collections.Generic;
using System.Text;

namespace DecoratorPattern
{
class Program
{
static void Main(string[] args)
{
ConcreteComponet c
= new ConcreteComponet();
ConcreteDecoratorA d1
= new ConcreteDecoratorA();
ConcreteDecoratorB d2
= new ConcreteDecoratorB();

d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();

Console.Read();
}
}
}

运行结果:

具体对象的操作

具体装饰对象A的操作New State

具体装饰对象B的操作