1.定义
以共享的方式高效的支持大量的细粒度对象,能够减少运行时对象实例的个数,节省内存。主要用于减少对象的创建,以节省内存提高性能。
2.使用场景及设计
2.1.使用场景
系统中需要大量类似的对象。例:需要展示100000个随机生成的坐标及其年龄。
2.2.设计
创建一个专门展示坐标及其年龄的对象,在使用一个manager类来创建所需要的对象。
3.测试代码
入口类
package com.glt.designpattern.flyWeight;
public class InitMain {
public static void main(String[] args) {
/**
* 蝇量模式/享元模式
* 以共享的方式高效的支持大量的细粒度对象,能够减少运行时对象实例的个数,节省内存
*/
TreeManager manager = new TreeManager();
manager.displayTrees();
}
}
package com.glt.designpattern.flyWeight;
/**
* 蝇量对象
*/
public class Tree {
public void display(int x, int y, int age) {
System.out.println("x=" + x);
System.out.println("y=" + y);
System.out.println("age=" + age);
}
}
package com.glt.designpattern.flyWeight;
/**
* 管理对象
*/
public class TreeManager {
int len = 100000;
int[][] treeArray = new int[len][3];
private Tree tree;
public TreeManager() {
tree = new Tree();
for (int i = 0; i < len; i++) {
treeArray[i] = new int[]{(int) Math.round(Math.random() * len), (int) Math.round(Math.random() * len), (int) Math.round(Math.random() * len) % 5};
}
}
public void displayTrees() {
for (int i = 0; i < len; i++) {
tree.display(treeArray[i][0], treeArray[i][1], treeArray[i][2]);
}
}
}
输出结果
x=58182
y=75606
age=2
x=91598
y=5026
age=2
…
4.总结
优点:
能够减少对象的创建,降低系统内存开销,提高系统的性能。
缺点:
蝇量对象内部和外部隔离性高,内部发生改变可能会影响到输出结果,出现意外情况。