原文地址:http://haolloyin.blog.51cto.com/1177454/458416/html
- 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());
- }
- }
- // 實際應用中能夠是用 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();
- // ...
- }