三、裝飾模式示例性代碼
以下示例性代碼實現了裝飾模式:
// Decorator pattern -- Structural example
using System;
// "Component"
abstract class Component
{
// Methods
abstract public void Operation();
}
// "ConcreteComponent"
class ConcreteComponent : Component
{
// Methods
override public void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
}
// "Decorator"
abstract class Decorator : Component
{
// FIElds
protected Component component;
// Methods
public void SetComponent( Component component )
{
this.component = component;
}
override public void Operation()
{
if( component != null )
component.Operation();
}
}
// "ConcreteDecoratorA"
class ConcreteDecoratorA : Decorator
{
// FIElds
private string addedState;
// Methods
override public void Operation()
{
base.Operation();
addedState = "new state";
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
}
// "ConcreteDecoratorB"
class ConcreteDecoratorB : Decorator
{
// Methods
override public void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("ConcreteDecoratorB.Operation()");
}
void AddedBehavior()
{
}
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
public static void Main( string[] args )
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
// Link decorators
d1.SetComponent( c );
d2.SetComponent( d1 );
d2.Operation();
}
}
上面的代碼在執行裝飾時是通過SetComponent方法實現的,在實際應用中,也有通過構造函數實現的,一個典型的創建過程可能如下:
new Decorator1(
new Decorator2(
new Decorator3(
new ConcreteComponent()
)
)
)
裝飾模式常常被稱為包裹模式,就是因為每一個具體裝飾類都將下一個具體裝飾類或者具體構件類包裹起來。