Design Pattern 13-Decorator

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值