享元模式是设计模式中少数几个以调高系统性能为目的的设计模式。它的核心思想是:如果在一个系统中存在多个相同的对象,那么只需共享一份对象的拷贝,而不必为每一次使用都创建新的对象。在享元模式中,由于需要构建和维护这些可以共享的对象,因此,常常会出现一个工厂类,用于维护和创建对象。
享元模式对性能提升的主要帮助有两点:
1.可以节省重复创建对象的开销,因为被享元模式维护的相同对象只会被创建一次,当对象创建比较耗时时,便可以节省大量时间;
2.由于创建对象的数量减少,所有对系统内存的需求也减少,这样使GC的压力也相应的降低,进而使系统拥有一个更健康的内存结构和更快的反应速度。
享元模式主要有享元工厂、抽象享元、具体享元和主函数几部分构成。各部分功能如下:
享元工厂是享元模式的核心,它需要确保系统可以共享相同的对象。享元模式的主要作用是复用大对虾(重量级对象),以减省内存空间和创建时间。享元模式的主要应用是SAAS系统(software as a service)。
抽象享元:
1publicinterfaceIReportManager {2publicString createReport();3}
具体享元:
1publicclassEmployeeReportManagerimplementsIReportManager {23PRivateString tenantId =null;4567publicEmployeeReportManager(String tenantId) {8this.tenantId =tenantId;9System.out.println("EmployeeReportManager.EmployeeReportManager()");10}11121314@Override15publicString createReport() {16return"This is a employee report";17}1819}
publicclassFinancialReportManagerimplementsIReportManager{privateString tenantId =null;publicFinancialReportManager(String tenantId) {this.tenantId =tenantId;
System.out.println("FinancialReportManager.FinancialReportManager()");
}
@OverridepublicString createReport() {return"This is a financial report";
}
}
享元工厂:
1publicclassReportManagerFactory {2privateMap<String,IReportManager> financialReportManager =newHashMap<String,IReportManager>();3privateMap<String,IReportManager> employeeReportManager =newHashMap<String,IReportManager>();45publicIReportManager getFinancialReportManager(String tenantId){6IReportManager iReportManager =financialReportManager.get(tenantId);7if(iReportManager==null){8iReportManager =newFinancialReportManager(tenantId);9}10returniReportManager;11}1213publicIReportManager getEmployeeReportManager(String tenantId){14IReportManager iReportManager =financialReportManager.get(tenantId);15if(iReportManager==null){16iReportManager =newFinancialReportManager(tenantId);17}18returniReportManager;19}2021}
main方法:
1publicclassTestClient {23publicstaticvoidmain(String[] args) {4ReportManagerFactory rmf =newReportManagerFactory();5IReportManager rm = rmf.getEmployeeReportManager("1233");6rmf.getEmployeeReportManager("1233");7System.out.println(rm.createReport());8}910}
另外,享元模式与对象池最大的区别就是,享元模式是不可相互替代的,他们各自有各种的含义和用途,而对象池中的对象是等价的,可以相互替换,如数据库连接池中的数据库连接。