欢迎光临
我们一直在努力

设计模式c#描述——装饰(Decorator)模-.NET教程,数据库应用

建站超值云服务器,限时71元/月

设计模式c#语言描述——装饰(decorator)模式

*本文参考了《java与模式》的部分内容,适合于设计模式的初学者。

装饰模式又名包装模式,以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。它使用原来被装饰的类的一个子类的实例,把客户端的调用委派到被装饰类,客户端并不会觉得对象在装饰前和装饰后有什么不同。在以下情况下应使用装饰模式:需要扩展一个类的功能,或给一个类增加附加责任。动态地给一个对象增加功能,这些功能可以再动态地撤销。需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

类图如下所示:

装饰模式包括如下角色:

抽象构件(component):给出一个抽象接口,以规范准备接收附加责任的对象。

具体构件(concrete component):定义一个将要接收附加责任的类。

装饰(decorator):持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口。

具体装饰(concrete decorator):负责给构件对象“贴上”附加的责任。

component:

public interface component

{

void sampleoperation();

}// end interface definition component

decorator:

public class decorator : component

{

private component component;

public decorator(component component)

{

this.component=component;

}

public virtual void sampleoperation()

{

component.sampleoperation();

}

}// end class definition decorator

concretecomponent:

public class concretecomponent : component

{

public void sampleoperation()

{

console.writeline ("concretecomponent sampleoperation");

}

}// end class definition concretecomponent

concretedecorator1:

public class concretedecorator1 : decorator

{

public concretedecorator1(component component):base(component)

{

}

override public void sampleoperation()

{

base.sampleoperation ();

console.writeline ("concretedecorator1 sampleoperation");

}

}// end class definition concretedecorator1

concretedecorator2:

public class concretedecorator2 : decorator

{

public concretedecorator2 (component component):base(component)

{

}

override public void sampleoperation()

{

base.sampleoperation ();

console.writeline ("concretedecorator2 sampleoperation");

}

}// end class definition concretedecorator2

client:

static void main(string[] args)

{

component component=new concretecomponent ();

component concretedecorator1=new concretedecorator1 (component); // 包装

component concretedecorator2=new concretedecorator2 (concretedecorator1);

concretedecorator2.sampleoperation ();

}

程序输出如下:

concretecomponent sampleoperation

concretedecorator1 sampleoperation

concretedecorator2 sampleoperation

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 设计模式c#描述——装饰(Decorator)模-.NET教程,数据库应用
分享到: 更多 (0)

相关推荐

  • 暂无文章