类设计2

    有了前面的学习,现在该是解决ReportService和PdfReportService类之间的依赖关系了。

    引入新的Container类:

public class Container {
	
	private static final Container _container = new Container();
	
	private Map<String, Object> components;
	
	private Container(){
		components = new HashMap<String, Object>();
		ReportGenerator generator = new PdfReportGenerator();
		components.put("ReportGenerator", generator);
		ReportService service = new ReportService();
		components.put("ReportService", service);
	}
	
	public static Container getInstance(){
		return _container;
	}
	
	public Object getComponents(String id){
		return components.get(id);
	}
	
}
public class ReportService {

	// private ReportGenerator generator = new PdfReportGenerator();
	private ReportGenerator generator = (ReportGenerator) Container
			.getInstance().getComponents("ReportGenerator");
	private int[][] data = new int[50][50];

	public void generateAnnulReport() {
		generator.generate(data);
	}

	public void generateMonthlyReport() {
		generator.generate(data);
	}

	public void generateDailyReport() {
		generator.generate(data);
	}

}
   这样ReportService就可以重用了,所有的对象管理都在container来管理了。

你可能感兴趣的:(设计)