有没有一种方法可以在没有样板代码的情况下在 Java 中实现转发对象模式?
由于封装被认为比继承更好(根据Effective Java 和其他来源),因此存在一种转发对象的模式。 (我相信装饰器模式是这个的同义词,但如果我错了,请不要对我大喊大叫!)
基本上,你编写这样的代码:
class public ForwardSomething extends Something {
private Something something=new Something();
public void somethingMethod1(){return something.somethingMethod1();}
public void somethingMethod2(){return something.somethingMethod2();}
/*Do same for the methods for all methods of Something that exist when you wrote Forward Something.*/
}
所以有很多样板代码。我们都知道“不要重复自己”是理想的选择。有没有一种不涉及样板代码的好方法来解决这个问题?
Since encapsulation is considered better than inheritance (according to Effective Java and other sources), there is a pattern of Forwarding an Object. (I believe the Decorator pattern is a synonym for this, but please don't yell at me if I'm wrong!)
Basically, you write code like this:
class public ForwardSomething extends Something {
private Something something=new Something();
public void somethingMethod1(){return something.somethingMethod1();}
public void somethingMethod2(){return something.somethingMethod2();}
/*Do same for the methods for all methods of Something that exist when you wrote Forward Something.*/
}
So there's a lot of boilerplate code. And we all know "Don't Repeat Yourself" is ideal. Is there a good way to approach this problem, that doesn't involve the boilerplate code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TL;DR:不,不是微不足道的。这是Java。
大多数 IDE 可以自动执行此操作。当我做大量工作时,我求助于“样板基类”来避免污染实际工作的代码。
您可以使用 Lombok 的
@Delegate
(文档)。TL;DR: No, not trivially. It's Java.
Most IDEs can do this automatically. I've resorted to "boilerplate baseclasses" to avoid polluting the code-that-does-real-work when I'm doing a lot of it.
You could use Lombok's
@Delegate
(docs), though.对于接口,您可以使用动态代理类 或者使用具体的类,您可以做一些技巧,例如使用 cglib (或类似asm)
With interfaces you could use a dynamic proxy class or with concrete classes you can do some trickery like dynamically writing the bytecode for a new subclass with cglib (or similar like asm)