我有一个名为 MilitaryReport 的类,它实现了 Reportable 接口(interface):
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 的类,它实现了 Reportable 接口(interface):
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();
}
问题就在这里。可报告是属于报告实例的策略。报告可以具有任何类型的可报告内容,例如军事、石油、驾驶员等。这些类型都实现相同的接口(interface),但具有独特的元素。
我可以将可报告项分配给报告,如下所示:
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);
但是当我稍后访问可报告时,我无法访问任何独特的方法。我只能访问接口(interface)中实现的方法。这不会编译:
report.reportable.uniqueAttribute();
问题是我不想将可报告的数据类型设置为 MilitaryReport。我希望数据类型是可报告的,因此我可以为其分配任何类型的可报告数据。同时,我想访问报告的独特方法。
如何绕过这个限制?另一种设计模式?
最佳答案
界面的整体思想是您不关心它是什么类型的可报告。当您在接口(interface)级别声明 Reportable
而不是 MilitaryReportable
时,您只能看到 Reportable
上声明的方法。如果您不想将其声明为 MilitaryReportable
,但您知道它是什么,则可以强制转换它:
((MilitaryReportable)report.reportable).someUniqueMethod()
关于java - 访问实现接口(interface)的类的独特方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30833643/