【问题标题】:Decorator pattern: Is it required that all decorators add value despite the sequence of initialization装饰器模式:是否要求所有装饰器都添加值,尽管初始化顺序
【发布时间】:2014-10-12 10:11:11
【问题描述】:

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

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.

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

欢迎提供任何相关信息。

问候,

【问题讨论】:

  • 设计模式是指导方针,不要担心那些微小的调整以使其更适合您的模型。没有人会因为装饰器模式的理论模型有点不同就说你不应该做一些有意义的事情。
  • 为什么需要ExecuteFunctionDecorator?对我来说executeFunction() 应该是Subject 中的一个抽象方法。操作该对象的客户端代码不知道它已被修饰,只会在其上调用executeFunction()。对于原始抽象及其所有子类家族已经应该提供的行为,您不需要额外的装饰器。

标签: java oop design-patterns decorator


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2023-04-08
    • 2018-03-10
    • 2019-02-23
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多