嗯,有点。我认为您没有充分利用面向对象的世界。使用抽象类,您可以实现默认的装饰器行为,例如包装所有无聊的包装。然后你可以简单地扩展这个 Decorator 抽象类并挑选你要覆盖的东西!
像这样的东西:
装饰者.java
public interface Decoratee {
public int methodA(int argument);
public int methodB(int argument);
}
装饰A.java
public class DecorateeA implements Decoratee {
private final Object arg1, arg2;
public Decoratee(Object arg1, Object arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
public int methodA(int argument){
return someInt;
}
public int methodB(int argument){
return someInt;
}
}
装饰器.java
public abstract class Decorator implements Decoratee {
private final Decoratee decoratee;
public Decorator(Decoratee decoratee){
this.decoratee = decoratee;
}
public int methodA(int argument){
return decoratee.methodA(argument);
}
public int methodB(int argument){
return decoratee.methodB(argument);;
}
}
装饰器A.java
public class DecoratorA extends Decorator {
public DecoratorA(Decoratee decoratee){
super(decoratee);
}
public int methodA(int argument){
return someOhterInt;
}
//methodB inherited from Decorator
}
装饰器B.java
public class DecoratorB extends Decorator {
public DecoratorB(Decoratee decoratee){
super(decoratee);
}
//methodA inherited from Decorator
public int methodB(int argument){
return someOhterInt;
}
}
是的,您仍然必须包装这些东西。这里的好处是,您只需将它们包装一次- 然后您可以构建装饰器,直到您脸色发青。
此外 - 如果您需要访问被装饰者的方法,您现在可以通过super
关键字调用它们:
public class DecoratorC extends Decorator {
public DecoratorC(Decoratee decoratee){
super(decoratee);
}
//methodA inherited from Decorator
public int methodB(int argument){
return someOhterInt + super.methodB(argument);
//super.methodB calls Decorator.methodB which calls decoratee.methodB;
}
}