原文地址:http://haolloyin.blog.51cto.com/1177454/458416/
问题描述:
解决方案:
实现方法:
根据上面所述,得到如下类图:
代码实现:
- interface ReportGenerator {
- public void generate(Table table);
- }
- class ExcelGenerator implements ReportGenerator {
- public void generate(Table table) {
- System.out.println("generate an Excel report ...");
- }
- }
- class PDFGenerator implements ReportGenerator {
- public void generate(Table table) {
- System.out.println("generate an PDF report ...");
- }
- }
- class ReportService {
- // 负责创建具体需要的报表生成器
- private ReportGenerator generator = new PDFGenerator();
- // private static ReportGenerator generator = new ExcelGenerator();
- public void getDailyReport(Date date) {
- table.setDate(date);
- // ...
- generator.generate(table);
- }
- public void getMonthlyReport(Month month) {
- table.setMonth(month);
- // ...
- generator.generate(table);
- }
- }
- public class Client {
- public static void main(String[] args) {
- ReportService reportService = new ReportService();
- reportService.getDailyReport(new Date());
- //reportService.getMonthlyReport(new Date());
- }
- }
问题描述:
解决方案:
引入容器
实现方法:
得到类图如下:
代码实现:
- class Container {
- // 以键-值对形式保存各种所需组件 Bean
- private static Map<String, Object> beans;
- public Container() {
- beans = new HashMap<String, Object>();
- // 创建、保存具体的报表生起器
- ReportGenerator reportGenerator = new PDFGenerator();
- beans.put("reportGenerator", reportGenerator);
- // 获取、管理 ReportService 的引用
- ReportService reportService = new ReportService();
- beans.put("reportService", reportService);
- }
- public static Object getBean(String id) {
- return beans.get(id);
- }
- }
- class ReportService {
- // 消除紧耦合关系,由容器取而代之
- // private static ReportGenerator generator = new PDFGenerator();
- private ReportGenerator generator = (ReportGenerator) Container.getBean("reportGenerator");
- public void getDailyReport(Date date) {
- table.setDate(date);
- generator.generate(table);
- }
- public void getMonthlyReport(Month month) {
- table.setMonth(month);
- generator.generate(table);
- }
- }
- public class Client {
- public static void main(String[] args) {
- Container container = new Container();
- ReportService reportService = (ReportService)Container.getBean("reportService");
- reportService.getDailyReport(new Date());
- //reportService.getMonthlyReport(new Date());
- }
- }
时序图大致如下:
效果:
问题描述:
解决方案:
引入
Service Locator
实现方法:
类图如下:
代码实现:
- // 实际应用中可以是用 interface 来提供统一接口
- class ServiceLocator {
- private static Container container = new Container();
- public static ReportGenerator getReportGenerator() {
- return (ReportGenerator)container.getBean("reportGeneraator");
- }
- }
- class ReportService {
- private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
- // ...
- }