我有一個叫MilitaryReport類,它實現了申報的接口:訪問的實現接口的類的唯一方法
public class MilitaryReporter implements Reportable {
public String reportable_type(){
return "MilitaryReport";
}
public String reportable_db_name() { return "military_reports"; }
public void setUniqueAttribute(int attr) { this.uniqueAttribute = attr; }
public int uniqueAttribute(){
return some_unique_attribute_to_military;
}
}
我有另一個類稱爲OilReport實現通報接口:
public class OilReport implements Reportable {
public String reportable_type(){
return "OilReport";
}
public String reportable_db_name() { return "oil_reports"; }
public int anotherUniqueAttribute(){
return some_unique_attribute_to_oil;
}
}
這是可報告的接口:
public interface Reportable {
public String reportable_type();
public String reportable_db_name();
}
這是問題。可報告是屬於報告實例的策略。報告可以具有任何類型的可報告的例如軍事,石油,驅動程序等。這些類型都實現相同的界面,但具有獨特的元素。
我能一個報告分配給一個報告爲這樣:
public class Report {
private Reportable reportable;
public void setReportable(Reportable reportable){ this.reportable = reportable; }
public Reportable reportable(){
return reportable;
}
}
然後在客戶端代碼中,我能夠分配一個報告到該實例:
MilitaryReporter reportable = new MilitaryReporter();
reportable.setUniqueAttribute(some_val);
report.setReportable(reportable);
但是,當我稍後訪問報告,我無法訪問任何獨特的方法。我只能訪問在接口中實現的方法。這將無法編譯:
report.reportable.uniqueAttribute();
問題是我不想將可報告的數據類型設置爲MilitaryReport。我希望數據類型是可報告的,所以我可以分配任何類型的可報告給它。同時,我想訪問報告的獨特方法。
我該如何解決這個限制?另一種設計模式?
:如果你不希望將其申報爲
MilitaryReportable
,但你知道它是什麼,你可以將它轉換或者你想用它做什麼是錯誤的。很難判斷哪一個是這種情況,但如果你確信你的界面,可能需要一個[訪問者模式](https://en.wikipedia.org/?title=Visitor_pattern)。 – biziclop這不是限制。這是你的糟糕設計,在這種情況下任何設計模式都是反模式。您應該閱讀以獲得對接口的基本理解:https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html,然後請繼續閱讀以瞭解接口概念的編程:http:/ /stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – John