如果你的方法並不需要從訪問私有狀態,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);
}
}