/*
* 動態給一個對象添加一些額外的職責,就象在牆上刷油漆.使用Decorator模式相比用生成子類方式達到功能的擴充顯得更爲靈活.
爲什麼使用Decorator?
我們通常可以使用繼承來實現功能的拓展,如果這些需要拓展的功能的種類很繁多,那麼勢必生成很多子類,增加系統的複雜性,同時,
使用繼承實現功能拓展,我們必須可預見這些拓展功能,這些功能是編譯時就確定了,是靜態的.
*/
using System;
using System.Collections ;
namespace Pattern
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public interface Work
{
void insert();
}
public class SquarePeg : Work
{
public void insert()
{
System.Console .WriteLine ("方形樁插入");
}
}
public class Decorator : Work
{
private Work work;
//額外增加的功能被打包在這個List中
private ArrayList others = new ArrayList();
//在構造器中使用組合new方式,引入Work對象;
public Decorator(Work work)
{
this.work=work;
others.Add ("挖坑");
others.Add ("釘木板");
}
public void insert()
{
newMethod();
}
//在新方法中,我們在insert之前增加其他方法,這裏次序先後是用戶靈活指定的
public void newMethod()
{
otherMethod();
work.insert();
}
public void otherMethod()
{
IEnumerator listIterator = others.GetEnumerator();
while (listIterator.MoveNext ())
{
System.Console .WriteLine(((String)(listIterator.Current )) + " 正在進行");
}
}
}
}
//裝飾模式
// Work squarePeg = new SquarePeg();
// Work decorator = new Decorator(squarePeg);
// decorator.insert();