[英]Same implementation in different subclasses
說我有以下情況:
abstract class A {
abstract method1();
abstract method2();
}
class B extends A {
method1() {
// implementation 1
}
method2() {
// implementation 3
}
}
class C extends A {
method1() {
// implementation 1
}
method2() {
// implementation 4
}
}
class D extends A {
method1() {
// implementation 2
}
method2() {
// implementation 4
}
}
底線:同一類的幾個子類,對不同的方法使用不同的方法實現。
問題是我在不同的子類中具有相同的實現。 我的問題是如何處理這些常見的實現?
做到這一點的邏輯方法是創建另一個抽象級別,但是只有在我使用一種具有通用實現的方法時才有效(因為Java沒有多重繼承)。 我還可以將最常用的實現放在超類中,而僅在其他類中以不同的方式實現。 但是,我不會這樣做,因為隨着時間的推移,最常見的實現可能會隨着其他類的添加而發生變化,此外,我想將方法抽象化為超類。
是否有某種模式可以“優雅地”解決我的問題?
您正在遇到經典的OOP問題,繼承層次結構變得笨拙:-)
我建議的解決方案:
我會建議組成。 考慮以下:
interface I1 {
method1();
}
abstract class A implements I1{
abstract method1();
abstract method2();
}
class CommonOperations implements I1 {
method1() {
// implementation 1
}
}
class B extends A {
CommonOperations common;
method1() {
common.method1();
}
method2() {
// implementation 3
}
}
class C extends A {
CommonOperations common;
method1() {
common.method1();
}
method2() {
// implementation 4
}
}
class D extends A {
method1() {
// implementation 2
}
method2() {
// implementation 4
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.