定义:提供了减少对象数量从而改善应用所需的对象结构的方式
运用共享技术有效支持大量细微度的对象
类型:结构型
应用场景:
系统底层的开发啊,以便解决系统的性能问题
系统有大量的相似对象,需要缓存池的场景
优点:
减少对象的创建,降低内存中对象的数量,降低系统的内存,提高效率
减少内存之外的其他资源占用
缺点:
关注内/外部状态,关注线程安全问题
使系统、程序的逻辑复杂化
public class EmployeeFactory { //final 不能别继承 对象池 private static final Map<String,Employee> EMPLOYEE_MAP=new HashMap<String, Employee>(); public static Employee getManager(String department){ Manager manager=(Manager) EMPLOYEE_MAP.get(department); if(manager==null){ manager=new Manager(department); System.out.print("创建部门经理:"+department); String reportContent=department+"部门汇报......"; manager.setReportContent(reportContent); System.out.println("创建报告:"+reportContent); EMPLOYEE_MAP.put(department,manager); } return manager; } }
public interface Employee { void report(); }
public class Manager implements Employee{ public void report() { System.out.println(reportContent); } private String department; private String reportContent; public void setReportContent(String reportContent) { this.reportContent = reportContent; } public Manager(String department) { this.department = department; } }
public class Test { private static final String departments[] = {"RD", "QA", "PM", "DB"}; public static void main(String[] args) { for (int i = 0; i < 10; i++) { String department = departments[(int) (Math.random() * departments.length)]; Manager manager = (Manager) EmployeeFactory.getManager(department); manager.report(); } } }
类图: