
using System;
using System.Collections.Generic;
using System.Text;
///Decorator(装饰器)模式 通过对已经存在的某些类进行装饰,以此来扩展一些功能。
///add by jzh 2007-04-24
namespace DesignPattern
{
/// <summary>
/// Component(抽象构件)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
/// </summary>
abstract class ComponentBus
{
public abstract void Draw();
}
/// <summary>
/// Concrete Component(具体构件)角色:定义一个将要接收附加责任的类。
/// </summary>
class ConcreteComponent : ComponentBus
{
private string strName;
public ConcreteComponent(string name)
{
strName = name;
}
public override void Draw()
{
Console.WriteLine("ConcreteComponent - {0}", strName);
}
}
/// <summary>
/// Decorator(装饰)角色:持有一个Component对象的实例,并定义一个与抽象构件接口一致的接口。
/// </summary>
abstract class Decorator : ComponentBus
{
protected ComponentBus ActualComponent;
public void SetComponent(ComponentBus c)
{
ActualComponent = c;
}
public override void Draw()
{
if (ActualComponent != null)
ActualComponent.Draw();
}
}
/// <summary>
/// Concrete Decorator(具体装饰)角色:负责给构件对象“贴上”附加的责任。
/// </summary>
class ConcreteDecorator : Decorator
{
private string strDecoratorName;
public ConcreteDecorator(string str)
{
strDecoratorName = str;
}
public override void Draw()
{
CustomDecoration();
base.Draw();
}
void CustomDecoration()
{
Console.WriteLine("In ConcreteDecorator: decoration goes here");
Console.WriteLine("{0}", strDecoratorName);
}
}
public class Client
{
ComponentBus Setup()
{
ConcreteComponent c = new ConcreteComponent("This is the real component");
ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");
d.SetComponent(c);
return d;
}
public static void Main(string[] args)
{
Client client = new Client();
ComponentBus c = client.Setup();
c.Draw();
Console.ReadLine();
}
}
}