2.1.3 享元模式

以提高性能为目的
核心思想:一个系统中存在多个相同的对象,只需共享一份对象的拷贝,而不必为每一次使用都创建新的对象。( 复用对象

主要角色:

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

与对象池的区别:

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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值