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.總結
優點:
能夠減少對象的創建,降低系統內存開銷,提高系統的性能。
缺點:
蠅量對象內部和外部隔離性高,內部發生改變可能會影響到輸出結果,出現意外情況。