example :
ExcelReport excelReport=new ExcelReport(); PDFReport pdfReport=new PDFReport(); excelReport.initialize(); excelReport.createReport(); excelReport.saveReport(); pdfReport.initialize(); pdfReport.createReport(); pdfReport.saveReport();
We can use polymorphism to reduce the coupling of the design.
Report excelReport=new ExcelReport(); Report pdfReport=new PDFReport(); excelReport.initialize(); excelReport.createReport(); excelReport.saveReport(); pdfReport.initialize(); pdfReport.createReport(); pdfReport.saveReport();
But still the caller have to know about the type of the objects. still there is no much advantage of using above design to reduce coupling.
There is another solution to reduce coupling dramatically. Which is called "Dependency Injection" . What we do here is, using a helper class to separate dependencies.
Report.java
package model; public interface Report { public void initialize(); public void createReport(); public void saveReport(); }
ExcelReport.java
package model; public class ExcelReport implements Report { @Override public void initialize() { System.out.println("-= Initializing Excel Report =-"); } @Override public void createReport() { System.out.println("-= Creating Excel Report =-"); } @Override public void saveReport() { System.out.println("-= Saving Excel Report =-"); } }
PDFReport.java
package model; public class PDFReport implements Report{ @Override public void initialize() { System.out.println("-= Initializing PDF Report =-"); } @Override public void createReport() { System.out.println("-= Creating PDF Report =-"); } @Override public void saveReport() { System.out.println("-= Saving PDF Report =-"); } }
ReportGenerator.java
package model; public class ReportGenerator { Report reoprt; public ReportGenerator(Report report){ this.reoprt=report; } public void generateReport(){ this.reoprt.createReport(); this.reoprt.saveReport(); } public void setReport(Report report){ this.reoprt=report; } }
DependancyInjectionDemo.java
import model.ExcelReport; import model.PDFReport; import model.Report; import model.ReportGenerator; public class DependancyInjectionDemo { /** * @param args */ public static void main(String[] args) { // without dependancy injection System.out .println("========Generating Reports Using Without Fependancy Injection========"); Report excelReport = new ExcelReport(); Report pdfReport = new PDFReport(); excelReport.initialize(); excelReport.createReport(); excelReport.saveReport(); pdfReport.initialize(); pdfReport.createReport(); pdfReport.saveReport(); System.out .println("========Generating Reports Using Fependancy Injection========"); // using dependancy injection ReportGenerator rpeortGen = new ReportGenerator(excelReport); // dependancy // injection // via // constructor rpeortGen.generateReport(); rpeortGen.setReport(pdfReport); // dependancy injection via mutator rpeortGen.generateReport(); } }
The above process can be simplified by using Spring.
0 comments:
Post a Comment