/*
Author: Jiangong SUN
*/
Decorators provide a flexible alternative to subclassing for extending functionality.
public class DecoratorPattern
{
/*
* decorator和wrapper是一個設計模式
* 用途:用來擴展已有類的功能
* 實現步驟:
* 先定義一個interface,然後建立一個類繼承這個接口,並實現接口裡的方法
* 建立一個包裝類繼承同一個接口,並在這個包裝類的構造器中使用接口的實例做參數。
* 建立實際包裝類繼承包裝類,重寫接口定義的方法,並可以創建自己特有的方法。
*/
public interface IComponent
{
void Operation();
}
public class ConcreteComponent : IComponent
{
public void Operation()
{
Console.WriteLine("ConcreteComponent operation");
}
}
public class Decorator : IComponent
{
private readonly IComponent _decoratedComponent;
public Decorator(IComponent iComponent)
{
_decoratedComponent = iComponent;
}
public void Operation()
{
_decoratedComponent.Operation();
}
}
public class ConcreteDecoratorA : Decorator
{
private string _addState;
public ConcreteDecoratorA(Decorator decorator)
: base(decorator)
{
}
public new void Operation()
{
base.Operation();
_addState = "New State";
Console.WriteLine("ConcreteDecoratorA.Operation");
}
public void CustomOperation()
{
Console.WriteLine("ConcreteDecoratorA custom Operation");
}
}
public static void Main()
{
ConcreteComponent concreteComponent = new ConcreteComponent();
concreteComponent.Operation();
Decorator decorator = new Decorator(concreteComponent);
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(decorator);
concreteDecoratorA.Operation();
concreteDecoratorA.CustomOperation();
Console.ReadKey();
}
}