Java generic interfaces with typesafe implementations

前端 未结 2 1549
长情又很酷
长情又很酷 2021-01-28 05:27

I\'m look for good alternatives to invoking a specific interface from a generic framework. I\'ll exemplify with code. Look to the question part, the example cod

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-28 05:57

    It seems to me like you're setting yourself up for a messy implementation by having three parallel inheritance hierarchies. May I ask, why can't you merge the Component and ReportBuilder's shared behavior? Effectively, you lose any abstraction on the components by forcing the service caller to know the subclass of the Report they want.

    I'd suggest simplifying the interface by minimizing or eliminating the parameters to buildReport()

     public class ReportService {
        ReportComponentRepository repo;
        List builders;
    
        public  T getReport(Class reportType) {
    
            // Build report from components using one of the registered builders
            for (ReportBuilder builder : builders) {
                if (builder.buildFor(reportType) {
                    //don't pass components - if there's a requirement 
                    //for a strongly typed subclass of Component, just 
                    //let the Report instance figure it out.
                    return builder.buildReport();
                }
            }
        }
    }
    
    
    //example use
    public class PDFReportBuilder implements ReportBuilder {
    
        ComponentSource componentSource;
    
        @Override
        public Report buildReport() {
             PDFReport report;
    
             for (PDFComponent component : componentSource.getPDFComponents()) {
                // assemble report ... 
                report.includeComponent(component);
                // no instanceof operations!
            }
    
            return report;
        }
    }
    

提交回复
热议问题