由于封装被认为比继承更好(根据 Effective Java 和其他来源),因此有一种转发对象的模式。 (我相信 Decorator 模式是这个的同义词,但如果我错了,请不要对我大喊大叫!)
基本上,您编写的代码如下:
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.*/
}
所以有很多样板代码。我们都知道“不要重复自己”是理想的。有没有不涉及样板代码的解决此问题的好方法?
最佳答案
TL;DR:不,不是微不足道的。它是 Java。
大多数 IDE 可以自动执行此操作。我已经求助于“样板基类”以避免在我做很多事情时污染实际工作的代码。
你可以使用 Lombok's @Delegate
(docs) , 不过。
关于java - 有没有一种方法可以在没有样板代码的情况下在 Java 中实现转发对象模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7906752/