我有一個胖接口:如何擺脫類型轉換?
public interface ISolver {
void solve();
String printMsgs();
boolean hasSolution();
int getLeaderId();
void add(Agent agent);
void add(int item);
void add(String item);
void addAll(Agent[] data);
void addAll(int[] data);
void addAll(String[] data);
public void initiateStartState();
Agent next();
boolean hasNext();
public List<Integer> getLeftSenders();
public List<Integer> getRightSenders();
public List<Integer> getCurrentLeaders();
Agent get(int idx);
}
兩個類都繼承這個接口:
public class OneDirectSolver extends Solver{
// some code..
}
public class BiDirectSolver extends Solver{
// some code..
}
類BiDirectSolver
使用在ISolver
聲明的所有方法,但OneDirectSolver
只使用一些方法。我想遵循界面分離原則。所以,我只留下了ISolver
的常用方法。方法是特定於BiDirectSolver
我在一個延伸ISolver
public interface ISolver {
void solve();
String printMsgs();
boolean hasSolution();
int getLeaderId();
void add(Agent agent);
void add(int item);
void add(String item);
void addAll(Agent[] data);
void addAll(int[] data);
void addAll(String[] data);
public void initiateStartState();
Agent next();
boolean hasNext();
}
public interface BiDirectSolvable extends ISolver {
public List<Integer> getLeftSenders();
public List<Integer> getRightSenders();
public List<Integer> getCurrentLeaders();
Agent get(int idx);
}
另一個接口移動但現在我有另一個問題。我試圖描述它。所以,我有2個客戶的BiDirectSolver
,並且OneDirectSolver
:
public class OneDirectPanel extends MyAbstractPanel {
private OneDirectSolvable solver;
public void setSolver(OneDirectSolver solver) {
this.solver = solver;
}
//some code..
}
public class BiDirectPanel extends MyAbstractPanel {
private BiDirectSolvable solver;
public void setSolver(BiDirectSolvable solver) {
this.solver = solver;
}
// some code
}
,現在我想以表示我創造OneDirectPanel的情況下,我的主類的片段,BiDirectPanel和ISolver:
public class GUI {
private ISolver solver;
private MyAbstractPanel panelWithPicture;
// a lot of code..
if (comboBoxForMode.getSelectedItem().equals("one direct")) {
solver = new OneDirectSolver();
panelWithPicture = new OneDirectPanel();
panelWithPicture.setSolver((OneDirectSolver)solver);
} else {
solver = new BiDirectSolver();
panelWithPicture = new BiDirectPanel();
panelWithPicture.setSolver((BiDirectSolvable)solver);
}
}
我看到只有一個解決方案:
if (comboBoxForMode.getSelectedItem().equals("one direct")) {
OneDirectSolver solver = new OneDirectSolver();
panelWithPicture = new OneDirectPanel();
panelWithPicture.setSolver(solver);
} else {
BiDirectSolvable solver = new BiDirectSolver();
panelWithPicture = new BiDirectPanel();
panelWithPicture.setSolver(solver);
}
但它是不可能的我,因爲我必須做一些actioms與求解它被創建後。我必須在所有情況下做到這一點。所以,我在主要課上做。 因此,在主類中我必須聲明類型ISolver的引用。
UPD: 最重要的是,如果我做一些動作,在主類求解它必須在OneDirectPanel和BiDirectPanel求解影響。
@JornVemee,對不起,我忘了一個重要的細節。我更新了我的問題。 –
@АлександрЕлизаров這應該還是可以的,它們是同一個對象。你不會通過稍後分配來複制它,只需引用它即可。 –
哦,是的! Excusme,我沒有注意到this.solver = solver這一行。是工作。非常感謝你! –