[英]Same implementation in different subclasses
Say I have the following scenario: 说我有以下情况:
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
}
}
Bottom line: several subclasses of the same class, using different method implementations for different methods. 底线:同一类的几个子类,对不同的方法使用不同的方法实现。
The problem is that I have the same implementation in different subclasses. 问题是我在不同的子类中具有相同的实现。 My question is what to do with these common implementations?
我的问题是如何处理这些常见的实现?
The logical way to do it would be to create another level of abstraction but that only works if I have one method with common implementations (since Java doesn't have multiple inheritence). 做到这一点的逻辑方法是创建另一个抽象级别,但是只有在我使用一种具有通用实现的方法时才有效(因为Java没有多重继承)。 I could also put the implementation most commonly used in the superclass and only implement it differently in the other classes.
我还可以将最常用的实现放在超类中,而仅在其他类中以不同的方式实现。 However, I wouldn't do that because in time the most common implementation might change with the addition of other classes, and besides, I'd like to keep the methods abstract in the superclass.
但是,我不会这样做,因为随着时间的推移,最常见的实现可能会随着其他类的添加而发生变化,此外,我想将方法抽象化为超类。
Is there some pattern that would solve my problem in an "elegant manner"? 是否有某种模式可以“优雅地”解决我的问题?
You're running into the classic OOP issue with inheritance heirarchies becoming unwieldy :-) 您正在遇到经典的OOP问题,继承层次结构变得笨拙:-)
My suggested solutions: 我建议的解决方案:
I would recommend Composition. 我会建议组成。 Consider the following:
考虑以下:
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.