如果你的方法并不需要从访问私有状态,d类中添加一个静态方法,并调用静态方法A,B,C
如果你的方法确实需要访问私有状态,看你是否能分解出需要通过添加一个包私人吸气每个班使用私有状态,然后使用方法A.
否则,试图分解出一些逻辑来共同接口而不是超类。
否则,请尝试委托给助手类。 (例如组合物而不是继承作为@Marcelo指示)
否则,重复的方法中的每个类A,B,C.
作为共同接口方法的一个例子,具有静态方法组合在D中:
interface MyThing
{
public void doMyThing(String subject);
public List<String> getThingNames();
}
class D
{
static void doSomethingComplicatedWithMyThing(MyThing thing)
{
for (String name : thing.getThingNames())
{
boolean useThing = /* complicated logic */
if (useThing)
thing.doMyThing(name);
}
}
}
class A extends SomeClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}
class B extends SomeOtherClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}
class C extends YetAnotherClass implements MyThing
{
/* implement methods of MyThing */
void doSomethingComplicated()
{
D.doSomethingComplicatedWithMyThing(this);
}
}