有没有一种方法可以在没有样板代码的情况下在 Java 中实现转发对象模式?

发布于 2024-12-12 05:17:48 字数 561 浏览 0 评论 0原文

由于封装被认为比继承更好(根据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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空名 2024-12-19 05:17:48

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.

守护在此方 2024-12-19 05:17:48

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文