gpt4 book ai didi

java - Java 或 Eclipse 可以轻松使用装饰器模式时不被更改的 'auto wrap' 类方法吗

转载 作者:行者123 更新时间:2023-11-29 09:02:08 28 4
gpt4 key购买 nike

我发现有几次我在考虑装饰器模式,并且很想不这样做,因为包装类方法以将功能向下传递到我正在装饰的类可能非常乏味。写作:

 public int methodA(int argument){
return decoratee.methodA(argument);
}

一遍又一遍地修改十几种方法,当我真的只对修改其中的一两个感兴趣时,这实在是太乏味了。另外,如果我向类/接口(interface)添加一个新方法,如果我想将它公开给所有人,我需要记住返回并将该方法添加到所有使用装饰器模式的类中。

似乎应该有更简单的方法来做到这一点。我的意思是从理论上讲,您可以实现一种语言功能来处理装饰器模式,这与我们处理扩展类的方式几乎完全相同;除了调用装饰类而不是调用 super 。如果调用装饰类的方法并且装饰器没有为它编写任何内容,则自动将调用传递给装饰类。如果装饰类要隐藏方法,只有装饰类要实现不同的逻辑,他才真正把方法写出来。也许有一些很好的注释可以让人们快速识别装饰类的哪些方法应该可用,哪些不应该可用

所以 有什么东西可以为我做这种逻辑吗?我的意思是我怀疑它是否像我上面描述的那样内置到 java laungae 本身,尽管它很酷,但它似乎不会经常出现以证明它是合理的。不过,至少 eclipse 会处理像这样的方法的自动换行吗?

最佳答案

嗯,有点。我认为您没有充分利用面向对象的世界。使用抽象类,您可以实现默认的装饰器行为,例如包装所有无聊的包装。然后您可以简单地扩展这个 Decorator 抽象类并挑选您要覆盖的东西!

像这样:

装饰器.java

public interface Decoratee {
public int methodA(int argument);
public int methodB(int argument);
}

DecorateeA.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;
}
}

关于java - Java 或 Eclipse 可以轻松使用装饰器模式时不被更改的 'auto wrap' 类方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16724464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com