设计模式系列:享元模式

概念

一个类的实例有多种 “虚拟实例”。 虚拟实例通过共享数据的方式存在。

实现

  • 类图:
    图片

Tree:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.littlehui.design.flyweight;

/**
* Created by littlehui on 2018/1/23.
*/
public class Tree {
private int x;
private int y;
private int age;

public Tree(int x, int y, int age) {
this.x = x;
this.y = y;
this.age = age;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public void display() {
System.out.println("坐标x:" + x + "坐标y:" + y + "年龄age:" + age);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.littlehui.design.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
* Created by littlehui on 2018/1/23.
*/
public class TreeManager {

Map<String, Tree> allTrees = new HashMap<String, Tree>();

public Tree createTree(int x, int y, int age) {
String treeHash = new StringBuffer().append(x).append(y).append(age).toString();
if (allTrees.get(treeHash) != null) {
return allTrees.get(treeHash);
} else {
Tree tree = new Tree(x, y, age);
allTrees.put(treeHash, tree);
return allTrees.get(treeHash);
}
}

public void displayAllTrees() {
for (String key : allTrees.keySet()) {
Tree tree = allTrees.get(key);
tree.display();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.littlehui.design.flyweight;

/**
* Created by littlehui on 2018/1/23.
*/
public class Client {

public static void main(String[] args) {
TreeManager treeManager = new TreeManager();
Tree tree1 = treeManager.createTree(1,2,3);
Tree tree2 = treeManager.createTree(1,2,3);
Tree tree3 = treeManager.createTree(1,2,4);

System.out.println("实例个数:" + "tree1, tree2, tree3");
System.out.println("真实实例个数:");
treeManager.displayAllTrees();
}
}

场景

在java应用中,会出现许多String a=”123”,String b=”123”之类的String类型的变量,如果只是小应用,到还好,假设是一个庞大的系统,有好多处都需要用定义String a=”223”,那开销可想而知,而JDK的开发者自然想到了这点,采用了享元模式解决创建大量相同String变量带来的开销问题

总结

享元模式,其功能是在运行时减少实例的个数,节省内存。当一个类有许多的实例,而这些实例能被统一个方法控制到时候,可以用享元模式。