1. 概述
2. 代码解析
public interface Employee {
void report();
}
public class Manager implements Employee {
private String department; // 内部状态
private String reportContent; // 外部状态
public Manager(String department) {
this.department = department;
}
public void setReportContent(String reportContent) {
this.reportContent = reportContent;
}
@Override
public void report() {
System.out.println(reportContent);
}
}
/**
* 享元模式:
* 1. 减少创建对象的次数.
* 2. 内部状态:就是不通过外部修改、传入的属性.
* 3. 外部状态:就是通过外部修改值, 影响对象的属性.
*/
public class EmployeeFactory {
private static Map<String, Employee> EMPLOYEE_GROUP = new HashMap<>();
public static Manager getManager(String department) {
Manager manager = (Manager) EMPLOYEE_GROUP.get(department);
if (manager == null) {
manager = new Manager(department);
System.out.println("Create manager: " + department);
String reportContent = "Report Content: .........";
manager.setReportContent(department + " ---> " + reportContent);
EMPLOYEE_GROUP.put(department, manager);
}
return manager;
}
}
public class FlyWeightTest {
public static void main(String[] args) {
String[] departments = {"RD", "QA", "PM"};
IntStream.range(0, 10).forEach(item -> {
String department = departments[(int)(Math.random() * departments.length)];
Manager manager = EmployeeFactory.getManager(department);
manager.report();
});
}
}
3. 源码使用
- JDK中
Integer
的IntegerCache
;只要Integer不是new出来的,在-128~127
中,都不会产生新的对象,而是从IntegerCache
中获取Integer对象,达到对象的重用。
来源:https://blog.csdn.net/weixin_38608626/article/details/100538130