[英]Implementing multiple interfaces with Java - is there a way to delegate?
我需要創建一個基類,它實現了許多方法的接口,例如下面的例子。
是否有更簡單的方法來委派這些方法調用而無需創建大量重復方法?
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
private InterFaceOne if1;
private InterFaceTwo if2;
public MultipleInterfaces() {
if1 = new ImplementingClassOne();
if2 = new ImplementingClassTwo();
}
@Override
public void classOneMethodOne { if1.methodOne(); }
@Override
public void classOneMethodTwo { if1.methodTwo(); }
/** Etc. */
@Override
public void classTwoMethodOne { if2.methodOne(); }
@Override
public void classTwoMethodTwo { if2.methodTwo(); }
/** Etc. */
}
如上所述,沒有辦法。 但是,有點像IDE可以自動生成委托方法。 例如Eclipse可以做到。 首先設置一個模板:
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
private InterFaceOne if1;
private InterFaceTwo if2;
}
然后右鍵單擊,選擇Source> Generate Delegate Methods並勾選if1
和if2
字段,然后單擊OK 。
另請參見以下屏幕:
有一種方法可以實現多個接口。
只需從另一個接口擴展一個接口或創建擴展預定義接口Ex的接口:
public interface PlnRow_CallBack extends OnDateSetListener {
public void Plan_Removed();
public BaseDB getDB();
}
現在我們有擴展另一個接口的接口在out類中使用只需使用這個實現兩個或更多接口的新接口
public class Calculator extends FragmentActivity implements PlnRow_CallBack {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
@Override
public void Plan_Removed() {
}
@Override
public BaseDB getDB() {
}
}
希望這可以幫助
很不幸的是,不行。
我們都急切地等待Java對擴展方法的支持
沒有好辦法。 您可以使用具有目標方法的處理程序的代理,並將其他所有內容委托給它們。 當然你必須使用工廠,因為沒有構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.