码迷,mamicode.com
首页 > 其他好文 > 详细

享元模式

时间:2019-01-06 18:02:50      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:public   ++   map   new   方式   ack   sys   ash   类图   

1.定义:提供了减少对象数量从而改善应用所需的对象结构的方式;
      运用共享技术有效地支持大量细粒度的对象。

2.类型:结构型

3.适用场景:常常应用于底层的开发,以便解决系统的性能问题;
        系统有大量相似对象、需要缓冲池的场景。

4.优点:减少对象的创建,降低内存中对象的数量,降低系统的内存,提高效率;
      减少内存之外的其他资源占用。

5.缺点:关注内/外部状态、关注线程安全问题;使系统、程序的逻辑复杂化。

6.扩展:内部状态、外部状态

7.相关设计模式:代理模式、单例模式

8.实例目录package

技术分享图片


9.实例UML类图

技术分享图片

10.代码

1 package com.geely.design.pattern.structural.flyweight;
2 
3 public interface Employee {
4     void report();
5 }
 1 package com.geely.design.pattern.structural.flyweight;
 2 
 3 public class Manager implements Employee {
 4     private String title = "部门经理";
 5     private String department;
 6     private String reportContent;
 7 
 8     public Manager(String department) {
 9         this.department = department;
10     }
11 
12     public void setReportContent(String reportContent) {
13         this.reportContent = reportContent;
14     }
15 
16     @Override
17     public void report() {
18         System.out.println(reportContent);
19     }
20 }
 1 package com.geely.design.pattern.structural.flyweight;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class EmployeeFactory {
 7     private static final Map<String,Employee> EMPLOYEE_MAP = new HashMap<>();
 8 
 9     public static Employee getManager(String department){
10         Manager manager = (Manager) EMPLOYEE_MAP.get(department);
11         if(manager == null){
12             manager = new Manager(department);
13             System.out.println("创建部门经理:" + department);
14             String reportContent = department + "部门汇报:此次报告的内容是。。。";
15             manager.setReportContent(reportContent);
16             System.out.println("创建报告:" + reportContent);
17             EMPLOYEE_MAP.put(department,manager);
18         }
19         return manager;
20     }
21 }
 1 package com.geely.design.pattern.structural.flyweight;
 2 
 3 public class Test {
 4     private static final String[] departments = {"RD", "QA", "PM", "BD"};
 5     public static void main(String[] args) {
 6         for (int i = 0; i < 10; i++){
 7             String department = departments[(int)(Math.random()*departments.length)];
 8             Manager manager = (Manager) EmployeeFactory.getManager(department);
 9             manager.report();
10         }
11 
12         Integer a = Integer.valueOf(100);//new Integer(100);
13         Integer b = 100;
14         Integer c = Integer.valueOf(1000);//new Integer(1000);
15         Integer d = 1000;
16         System.out.println("a==b:"+(a==b));
17         System.out.println("c==d:"+(c==d));
18     }
19 }

 

享元模式

标签:public   ++   map   new   方式   ack   sys   ash   类图   

原文地址:https://www.cnblogs.com/linbq1911/p/10229198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!