java - 装饰器模式: Is it required that all decorators add value despite the sequence of initialization

标签 java oop design-patterns decorator

我有一个关于装饰器及其初始化顺序的问题。 是否要求每个装饰器都可以由其他装饰器扩展,或者如果扩展装饰器有限制也可以。例如:

Subject subject = new Subject();
decorator       = new ErrorHandlingDecorator(subject); //Extends for error handling, when error is detected it interupt the current thread.
decorator       = new ExecuteFunctionDecorator(decorator); //Execute a function and run the executeFunction() on his parent.

decorator.executeFunction();

这里,ExecuteFunctionDecorator 可以将结果传递给 ErrorHandlingDecorator,因为它首先执行该函数。但是,当您像下面的代码一样初始化它时,ErrorHandlingDecorator 就没用了,因为它首先检查错误,然后执行该函数。

Subject subject  = new Subject();
decorator        = new ExecuteFunctionDecorator(subject); //Execute a function and run the executeFunction() on his parent.
decorator        = new ErrorHandlingDecorator(decorator); //Extends for error handling, when error is detected it interupt the current thread.

所以我的问题是:这个例子仍然是一个装饰器,还是要求所有装饰器都添加值,尽管初始化顺序如何,或者装饰器在“不正确”的初始化之后可能毫无意义?

欢迎提供任何相关信息。

问候,

最佳答案

装饰器的一个经典示例(我认为它来自 GOF 书中)是 UI 应用程序中的小部件或面板,可以通过进一步的样式(例如边框)来增强(或装饰)。

想象两种不同的装饰器,一种使用 1 像素大小的边框装饰矩形小部件,另一种使用 5 像素大小的虚线边框。

您是否期望 (1) new DashedBorder(new Border(new Panel())) 看起来与 (2) new Border(new DashedBorder(new Panel()) 相同)?我不会。在第一种情况下,我期望 1 像素大小的边框由 5 像素大小的虚线边框封装,而在第二种情况下,结果反之亦然。

装饰者做他们所谓的事情。它们装饰你的物体。用两种不同的东西装饰一个对象可能会导致相同的结果,但它们不是必须的。

关于java - 装饰器模式: Is it required that all decorators add value despite the sequence of initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25381228/

相关文章:

java - 在 64 位 Windows 中使用 32 位 Java

c++ - 如何正确扩展类

android - 这是使用什么模式?

java - 在 Scala 中通过 SimpleDateFormat 转换后如何保持 DateTime 为 DateTime 格式?

java - 如何打包java库,当jar文件分发到另一台计算机时自动工作?

javascript - 如何从另一个对象调用一个对象的方法?

java - API 入口背后的设计决策

c++ - 使用抽象接口(interface)和向下转换所需的指导

Ruby 构建器模式或库

java - Maven bundle 插件配置