2.1.3 享元模式

来源:互联网 发布:悟空遥控器有线网络 编辑:程序博客网 时间:2024/05/06 21:05
以提高性能为目的
核心思想:一个系统中存在多个相同的对象,只需共享一份对象的拷贝,而不必为每一次使用都创建新的对象。(复用对象

主要角色:

享元工厂:创建具体享元类并维护相同的享元对象,内部实现类似单例模式,请求的对象已存在时直接返回对象,没有则创建(维护一个对象列表
抽象享元:共享对象的业务接口
具体享元类:实现抽象享元类,完成具体的逻辑
主函数:通过享元工厂获取对象

与对象池的区别:

对象池里所有对象均等价,可相互替代
享元工厂里任何两个对象都不能相互替代

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());}


0 0