/*
* 动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用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();