以提高性能爲目的
核心思想:一個系統中存在多個相同的對象,只需共享一份對象的拷貝,而不必爲每一次使用都創建新的對象。(複用對象)
抽象享元:共享對象的業務接口
具體享元類:實現抽象享元類,完成具體的邏輯
主函數:通過享元工廠獲取對象
享元工廠裏任何兩個對象都不能相互替代
享元類
享元工廠
主函數
核心思想:一個系統中存在多個相同的對象,只需共享一份對象的拷貝,而不必爲每一次使用都創建新的對象。(複用對象)
主要角色:
享元工廠:創建具體享元類並維護相同的享元對象,內部實現類似單例模式,請求的對象已存在時直接返回對象,沒有則創建(維護一個對象列表)抽象享元:共享對象的業務接口
具體享元類:實現抽象享元類,完成具體的邏輯
主函數:通過享元工廠獲取對象
與對象池的區別:
對象池裏所有對象均等價,可相互替代享元工廠裏任何兩個對象都不能相互替代
Example:
抽象享元public interface IReportManager{
public String createReport();
}
享元類
public class FinancialReportManager implements IReportManager{
private String id=null;
public FinancialReportManager(String id){
this.id = id;
}
@Override
public String createReport(){
return "a financial report";
}
}
public class EmployeeReportManager implements IReportManager{
private String id = null;
public EmployeeReportManager(String id){
this.id=id;
}
@Override
public String createReport(){
return "a employee report";
}
}
享元工廠
public class ReportManagerFactory{
Map<String,IReportManager> financialReportTable=new HashMap<String,IReportManager>();
Map<String,IReportManager> employeeReportTable=new HashMap<String,IReportManager>();
public IReportManager getFinancialReportManager(String id){
IReportManager r = financialReportTable.get(id);
if(r==null){
r=new FinancialReportManager(id);
financialReportTable.put(id,r);
}
return r;
}
public IReportManager getEmployeeReportManager(String id){
IReportManager r = employeeReportTable.get(id);
if(r==null){
r=new EmployeeReportManager(id);
employeeReportTable.put(id,r);
}
return r;
}
}
主函數
public static void main(String[] args){
ReportManagerFactory rmf = new ReportManagerFactory();
IReportManager rm = rmf.getFinancialReportManager("A");
System.out.println(rm.createReport());
}