原文地址:http://haolloyin.blog.51cto.com/1177454/458416/
问题描述:
解决方案:
实现方法:
根据上面所述,得到如下类图:
代码实现:
- interfaceReportGenerator{
- publicvoidgenerate(Tabletable);
- }
- classExcelGeneratorimplementsReportGenerator{
- voidgenerate(Tabletable){
- System.out.println("generateanExcelreport...");
- }
- }
- classPDFGeneratorvoidgenerate(Tabletable){
- System.out.println("generateanPDFreport...");
- }
- }
- classReportService{
- //负责创建具体需要的报表生成器
- privateReportGeneratorgenerator=newPDFGenerator();
- //privatestaticReportGeneratorgenerator=newExcelGenerator();
- voidgetDailyReport(Datedate){
- table.setDate(date);
- //...
- generator.generate(table);
- }
- voidgetMonthlyReport(Monthmonth){
- table.setMonth(month);
- //...
- generator.generate(table);
- }
- }
- classClient{
- staticvoidmain(String[]args){
- ReportServicereportService=newReportService();
- reportService.getDailyReport(newDate());
- //reportService.getMonthlyReport(newDate());
- }
- }
问题描述:
解决方案:
引入容器
实现方法:
得到类图如下:
代码实现:
- classContainer{
- //以键-值对形式保存各种所需组件Bean
- privatestaticMap<String,Object>beans;
- publicContainer(){
- beans=newHashMap<String,Object>();
- //创建、保存具体的报表生起器
- ReportGeneratorreportGenerator=newPDFGenerator();
- beans.put("reportGenerator",reportGenerator);
- //获取、管理ReportService的引用
- ReportServicereportService=newReportService();
- beans.put("reportService",reportService);
- }
- staticObjectgetBean(Stringid){
- returnbeans.get(id);
- }
- }
- //消除紧耦合关系,由容器取而代之
- //privatestaticReportGeneratorgenerator=newPDFGenerator();
- privateReportGeneratorgenerator=(ReportGenerator)Container.getBean("reportGenerator");
- voidgetDailyReport(Datedate){
- table.setDate(date);
- generator.generate(table);
- }
- voidgetMonthlyReport(Monthmonth){
- table.setMonth(month);
- generator.generate(table);
- }
- }
- voidmain(String[]args){
- Containercontainer=newContainer();
- ReportServicereportService=(ReportService)Container.getBean("reportService");
- reportService.getDailyReport(//reportService.getMonthlyReport(newDate());
- }
- }
时序图大致如下:
效果:
问题描述:
实现方法:
类图如下:
代码实现:
原文链接:https://www.f2er.com/javaschema/283877.html
- //实际应用中可以是用interface来提供统一接口
- classServiceLocator{
- staticContainercontainer=newContainer();
- staticReportGeneratorgetReportGenerator(){
- return(ReportGenerator)container.getBean("reportGeneraator");
- }
- }
- privateReportGeneratorreportGenerator=ServiceLocator.getReportGenerator();
- //...
- }