享元模式,是常用的設計模式之一,它通過對面向對象程序設計中的粒度單位的管理,達到提高系統性能的目的.所以對享元模式的學習是很有必要的, 下面通過一個例子對享元模式談談本人對享元模式的理解.
假設有這樣一個場景:
有一個共享的人事管理系統服務,被A,B,C,三個公司員工所共享.這三個公司享有自己獨立的數據庫.我們給每個員工的工資查詢提供了接口,這時候爲了提高系統性能就可以引入享元設計.
系統結構設計如下圖:
具體實現如下:
首先我們定義一個IReportManager接口,代碼如下:
public interface IReportCreate {
public String createReport();
}
我們就可以定義工作類來實現它.這裏我定義了FinancialReportManager和EmployeeReportManager兩個類.
public class EmployeeReportManager implements IReportCreate {
@Override
public String createReport() {
// TODO Auto-generated method stub
System.out.println("create Employee report....");
return "員工報表生成";
}
}
public class FinancialReportManager implements IReportCreate{
@Override
public String createReport() {
// TODO Auto-generated method stub
System.out.println("create financialReport。。。");
return "財務報表生成";
}
}
關鍵是定義一個工廠類ReportManagerFactory,設計思路是,定義方法去獲得想要的業務類的實例,這裏我們定義對應的Map來存儲生成的實例,根據對應的key值.
代碼:
import java.util.HashMap;
import java.util.Map;
public class ReportManagerFactory {
Map< String, IReportCreate> financialReportManagerMap=new HashMap<String, IReportCreate>();
Map< String, IReportCreate> employeeReportManagerMap=new HashMap<String, IReportCreate>();
public IReportCreate getEmployeeReportManager(String tenantid) {
EmployeeReportManager employeeReportManager=(EmployeeReportManager) employeeReportManagerMap.get(tenantid);
if (employeeReportManager==null) {
employeeReportManager=new EmployeeReportManager();
employeeReportManagerMap.put(tenantid, employeeReportManager);
}
return employeeReportManager;
}
public IReportCreate getFinancialReportManager(String tenantid) {
FinancialReportManager financialReportManager=(FinancialReportManager) financialReportManagerMap.get(tenantid);
if (financialReportManager==null) {
financialReportManager=new FinancialReportManager();
financialReportManagerMap.put(tenantid, financialReportManager);
}
return financialReportManager;
}
}
這就是一個簡單的享元模式的例子,本人還寫了相應的測試,
代碼如下:
public class TestReportManager {
public static void main(String[] args) {
ReportManagerFactory reportManagerFactory= new ReportManagerFactory();
IReportCreate iReportCreate=reportManagerFactory.getEmployeeReportManager("a");
System.out.println(iReportCreate);
String s=iReportCreate.createReport();
System.out.println(s);
IReportCreate iReportCreate2=reportManagerFactory.getFinancialReportManager("a");
System.out.println(iReportCreate2);
String string=iReportCreate2.createReport();
System.out.println(string);
iReportCreate=reportManagerFactory.getEmployeeReportManager("a");
System.out.println(iReportCreate);
}
}
運行結果: