![](/img/trans.png)
[英]Method Calls from Child Class objects in arraylist of parent class Java
[英]Java wrap a child class method such that the parent method gets called first and then calls child class method
我有一個 class 有很多方法。 這個 class 被復制到幾個不同的地方,每種方法的作用略有不同。 What I want to do is move the common code into a class with similar method signatures, but the parameter is a base class that the object in the parameter of the other class inherits. 當調用繼承的 class 中的方法時,我希望它重定向到基本的 class 方法,執行該代碼,然后以某種方式回調到繼承的 class 方法。 我無法提供確切的代碼,但我希望這個例子就足夠了。
class BaseTableVersion{
Long getId();
void setId(Long id);
String getVersion();
void setVersion(String version);
TableType getTableType();
}
class TableVersion extends BaseTableVersion{
Long getVersionNumber();
void setVersionNumber(Long versionNumber);
}
//this class needs to exists in some capacity. I can't make it inherit a class as it is now because
//it already inherits another class (which I can't show or change) and java doesn't support multiple.
// inheritence. I can add members or change methods
class TableVersionRules{
void create(TableVersion tableVersion){
//do stuff
}
void versionChanged(TableVersion tableVersion){
//do stuff
}
}
//this class doesnt need to exists, its just to hopefully illustrate what i want.
class BaseTableVersionRules<B extends BaseTableVersion>{
void create(B tableVersion){
//do stuff
//call TableVersionRules.create(tableVersion) somehow
}
void versionChanged(B tableVersion){
//do stuff
//call TableVersionRules.versionChanged(tableVersion) somehow
}
}
因此,從概念上講,我想要以某種方式鏈接 TableVersionRules 和 BaseTableVersionRules,這樣當調用 TableVersionRules.versionChanged 時,它將首先調用 BaseTableVersionRules.versionChanged,然后執行 TableVersionRules.versionChanged 中的操作。 我可以為此使用什么設計模式,或者這是否違反了多態性?
它看起來像一個 inheritance 與子 class 調用父 class 使用“超級”關鍵字。 像這樣的東西:
class TableVersionRules extends BaseTableVersionRules {
void versionChanged(...) {
super.versionChanged(...);
// Do some more stuff here.
}
}
“超級”將從父 class 調用實現,然后您仍然可以在此處添加更多代碼。
是否有意義?
更新:如果您不能使用“擴展”,因為 class 已經擴展了其他內容,請嘗試使用本地字段:
class TableVersionRules extends SomeOtherStuffThatNeedsToBeThere {
private final BaseTableVersionRules delegate;
void versionChanged(...) {
delegate.versionChanged(...);
// Do some more stuff here.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.