作用
系统有大量相似对象,需要缓冲池的场景
提供减少对象数量,降低内存中对象的数量,从而改善应用所需的对象结构的方式
应用于底层开发,以便解决系统性能问题
池化技术
Demo设计
部门做汇报,但并不需要每次进行汇报操作时都需要创建部门类
部门类
先定义一个部门接口,提供一个汇报方法
public interface Employee {
void report();
}
创建一个类继承部门接口 部门管理类,用来进行汇报
@Setter
public class Manager implements Employee {
private String department;
private String reportContent;
public Manager(String department) {
this.department = department;
}
@Override
public void report() {
System.out.println(reportContent);
}
}
与工厂模式结合
获取部门对象,还要避免每次请求都new一次对象
使用hashmap来保存对象,通过判断来确保new对象次数降低
public class EmployeeFactory {
private static final Map<String, Employee> EMPLOYEE_MAP = new ConcurrentHashMap<>();
public static Employee getManager(String department) {
Manager manager = (Manager) EMPLOYEE_MAP.get(department);
if (manager == null) {
//new对象时会先打印这句话
System.out.println("创建部门:" + department);
manager = new Manager(department);
manager.setReportContent(department + " : 部门汇报");
EMPLOYEE_MAP.put(department, manager);
}
return manager;
}
}
测试方法
随机获取部门,然后做汇报
public static void main(String[] args) {
//部门名称数组
String[] departments = {"DR", "BCMS", "AUTO", "OBMS"};
for (int i = 0; i < 10; i++) {
String department = departments[(int) (Math.random() * departments.length)];
Employee manager = EmployeeFactory.getManager(department);
manager.report();
}
}
一共调用10次但只new了四次对象
JDK中享元模式的运用
Integer中的运用
数值大于IntegerCache的最大值或小于最低值才new Integer对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}