享元模式,是常用的设计模式之一,它通过对面向对象程序设计中的粒度单位的管理,达到提高系统性能的目的.所以对享元模式的学习是很有必要的, 下面通过一个例子对享元模式谈谈本人对享元模式的理解.
假设有这样一个场景:
有一个共享的人事管理系统服务,被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);
}
}
运行结果: