原文地址:http://haolloyin.blog.51cto.com/1177454/458416/
问题描述:
解决方案:
实现方法:
根据上面所述,得到如下类图:
代码实现:
- interface ReportGenerator {
- public void generate(Table table);
- }
- class ExcelGenerator implements ReportGenerator {
- void generate(Table table) {
- System.out.println("generate an Excel report ...");
- }
- }
- class PDFGenerator void generate(Table table) {
- System.out.println("generate an PDF report ...");
- }
- }
- class ReportService {
- // 负责创建具体需要的报表生成器
- private ReportGenerator generator = new PDFGenerator();
- // private static ReportGenerator generator = new ExcelGenerator();
- void getDailyReport(Date date) {
- table.setDate(date);
- // ...
- generator.generate(table);
- }
- void getMonthlyReport(Month month) {
- table.setMonth(month);
- // ...
- generator.generate(table);
- }
- }
- class Client {
- static void main(String[] args) {
- ReportService reportService = new ReportService();
- reportService.getDailyReport(new Date());
- //reportService.getMonthlyReport(new Date());
- }
- }
问题描述:
解决方案:
引入容器
实现方法:
得到类图如下:
代码实现:
class Container {
时序图大致如下:
效果:
然而,观察上面的类图,很容易发现 ReportService 与 Container 之间存在双向关联,彼此互相有依赖关系。并且,如果想要重用 ReportService,由于它也是直接依赖于单独一个 Container 的具体查找逻辑。若其他容器具体不同的组件查找机制(如 JNDI),此时重用 ReportService 意味着需要修改 Container 的内部查找逻辑。
// 实际应用中可以是用 interface 来提供统一接口
class ServiceLocator {
static Container container = new Container();
static ReportGenerator getReportGenerator() {
return (ReportGenerator)container.getBean("reportGeneraator");
}
}
class ReportService {
private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
// ...
}
实现方法:
类图如下:
代码实现:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。