2015-06-14 84 views
0

我有一个叫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。我希望数据类型是可报告的,所以我可以分配任何类型的可报告给它。同时,我想访问报告的独特方法。

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

+0

:如果你不希望将其申报为MilitaryReportable,但你知道它是什么,你可以将它转换或者你想用它做什么是错误的。很难判断哪一个是这种情况,但如果你确信你的界面,可能需要一个[访问者模式](https://en.wikipedia.org/?title=Visitor_pattern)。 – biziclop

+0

这不是限制。这是你的糟糕设计,在这种情况下任何设计模式都是反模式。您应该阅读以获得对接口的基本理解: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

回答

3

接口的整体思想是你不关心它是什么类型的可报告的。当您在界面级声明时,Reportable而不是MilitaryReportable,您只能看到在Reportable上声明的方法。如果您需要访问不是由接口定义,那么无论你的界面是错误的方法

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

相关问题