有没有办法在没有样板代码的情况下在Java中实现转发对象模式?

时间:2011-10-26 17:52:54

标签: java dry encapsulation

由于封装被认为比继承更好(根据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.*/
}

所以有很多样板代码。我们都知道“不要重复自己”是理想的。有没有一种很好的方法来解决这个问题,这不涉及样板代码?

2 个答案:

答案 0 :(得分:4)

TL; DR:不,不是琐碎的。这是Java。

大多数IDE都可以自动执行此操作。我已经使用“样板基类”来避免污染代码 - 当我做很多事情时它会真正起作用。

但您可以使用Lombok's @Delegate (docs)

答案 1 :(得分:2)

使用接口,您可以使用dynamic proxy class或具体类,您可以做一些技巧,例如使用cglib(或类似asm的类似动态编写新子类的字节码)