クラス設計2

1466 ワード

先の学習があって、今は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で管理されます.