如想让某个类的一个实例能用来提供许多“虚拟实例”,就使用享元模式。
示例—景观设计
为客户的家庭景观做设计软件,需要新增树作为点缀。树有一个XY坐标位置,而且可以根据树的年龄动态地将自己绘制出来。用户可能要在他们的家庭景观设计中有非常非常多的树,所以每棵树的实例都要维护自己的状态,但引发了不易集中管理的问题。需要重新设计成一个实例就可以集中管理的模式。
UML图表示
代码演示
树
package Flyweight;
public class Tree {
void display(int x, int y, int age){
System.out.println("The "+ age +" years old tree is being painted at " + x + "," + y + ". ");
}
}
树管理类
package Flyweight;
public class TreeManager {
private final int MAX_INDEX = 1000;
int[][] treeArray = new int[MAX_INDEX][3];
int currentIndex = 0;
void newTree(int x, int y, int age){
if (currentIndex == MAX_INDEX){
System.out.println("Oops, you can't add any tree!!!");
return;
}
treeArray[currentIndex][0] = x;
treeArray[currentIndex][1] = y;
treeArray[currentIndex][2] = age;
currentIndex++;
}
void displayTrees(){
Tree tree = new Tree();
for (int i = 0; i <= currentIndex - 1; i++){
tree.display(treeArray[i][0],treeArray[i][1],treeArray[i][2]);
}
}
}
测试代码
package Flyweight;
public class FlyweightDriver {
public static void main(String[] args) {
TreeManager treeManager = new TreeManager();
treeManager.newTree(0,0,1);
treeManager.newTree(0,1,1);
treeManager.newTree(0,2,3);
treeManager.newTree(0,3,2);
treeManager.newTree(0,4,4);
treeManager.newTree(0,5,2);
treeManager.newTree(0,6,2);
treeManager.newTree(0,7,3);
treeManager.newTree(0,8,4);
treeManager.newTree(0,9,2);
treeManager.displayTrees();
}
}
测试结果
The 1 years old tree is being painted at 0,0.
The 1 years old tree is being painted at 0,1.
The 3 years old tree is being painted at 0,2.
The 2 years old tree is being painted at 0,3.
The 4 years old tree is being painted at 0,4.
The 2 years old tree is being painted at 0,5.
The 2 years old tree is being painted at 0,6.
The 3 years old tree is being painted at 0,7.
The 4 years old tree is being painted at 0,8.
The 2 years old tree is being painted at 0,9.