设计模式-享元设计

           享元模式,是常用的设计模式之一,它通过对面向对象程序设计中的粒度单位的管理,达到提高系统性能的目的.所以对享元模式的学习是很有必要的, 下面通过一个例子对享元模式谈谈本人对享元模式的理解.

   假设有这样一个场景:

          有一个共享的人事管理系统服务,被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);
}
}

运行结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值