由於封裝被認爲比繼承更好(根據Effective Java和其他來源),因此存在轉發對象的模式。 (我相信Decorator模式是它的一個同義詞,但請不要對我大喊如果我錯了!)有沒有一種方法來實現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.*/
}
所以有很多的樣板代碼。我們都知道「不要重複自己」是理想的。有沒有解決這個問題的好方法,不涉及樣板代碼?
(若延續的東西,你已經擁有了方法 - 合成子類的目的是什麼?你的意思是implements和一個新的SomethingImpl,而不是你在這裏編寫的東西?) –