我注意到,在说明装饰器模式的所有示例中,都有一个基类/接口(interface),并且有一个继承/实现它的装饰器类,之后,所有装饰类都扩展了装饰器类。大致如下:
Interface Window > WindowDecorator > WindowDecorator > VerticalScrollBarDecorator
the above hierarchy was taken from Wikipedia's Design Pattern Page.
The thing is, I want decorate some "Operation" classes, and have something along the following hierarchy :
root class is Operation
decorated classes could be Operation1, Operation2, and so forth.
I would have a constructor taking an Operation object in my Operation class, like this :
public Operation(Operation op)
{
this.op = op;
}
一个执行操作(每个子类都会重写)的抽象方法(我们称之为 doOperation),以及另一个调用“存储”对象的 doOperation 的方法,例如this(位于基类中):
public void executeOperation(some_args_here)
{
if(op != null)
op.doOperation(); // call stored object's doOperation first
doOperation(); //execute this operation
}
问题是,当我可以完成OperationDecorator 类在基类中可以做的所有事情时,我真的不认为这里需要OperationDecorator 类。如果我这样使用装饰器模式,我是否滥用了它?我是否错过了它的一些功能?
最佳答案
装饰器模式用于在运行时为对象提供特殊功能。 (假设对象已经存在,并且在某些情况下需要添加新功能)。
因此,Decorator类实现并聚合了现有的Base类,以便可以扩展操作。 Base 类将保持不变,当需要特殊行为时,通过提供 BaseClass 的实例来使用 DecoratorClass。
在您的情况下,方法名称不同。基类的用户(不知道装饰类)可能会感到困惑是使用 doOperation
还是 executeOperation
。
关于java - 像这样使用装饰器模式是不是错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/979956/