访问实现接口的类的唯一方法

时间:2015-06-14 19:33:33

标签: java

我有一个名为MilitaryReport的类,它实现了Reportable接口:

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接口:

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();
}

这就是问题所在。 reportable是属于Report实例的策略。报告可以包含任何类型的可报告,例如军事,石油,司机等。这些类型都实现相同的界面,但具有独特的元素。

我可以将报告分配给报告:

public class Report {

    private Reportable reportable;

    public void setReportable(Reportable reportable){ this.reportable = reportable; }

    public Reportable reportable(){
        return reportable;
    }
}

然后在客户端代码中,我可以为此实例分配一个reportable:

MilitaryReporter reportable = new MilitaryReporter();
reportable.setUniqueAttribute(some_val);
report.setReportable(reportable);

但是当我稍后访问reportable时,我无法访问任何独特的方法。我只能访问界面中实现的方法。这不会编译:

report.reportable.uniqueAttribute();

问题是我不想将可报告的数据类型设置为MilitaryReport。我希望数据类型是可报告的,因此我可以为其分配任何类型的可报告。与此同时,我想访问报告的独特方法。

我如何解决这个限制?另一种设计模式?

1 个答案:

答案 0 :(得分:3)

界面的整个想法是你不关心它是什么类型的可报告。当您在界面级别Reportable而不是MilitaryReportable声明它时,您只能看到Reportable上声明的方法。如果您不想将其声明为MilitaryReportable,但您知道它是什么,那么您可以将其转换为:

((MilitaryReportable)report.reportable).someUniqueMethod()