【发布时间】: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