蝇量模式
蝇量模式:通过共享的方式高效地支持大量的细粒度的对象。
优点:
减少运行时的对象的实例个数。
将许多“虚拟”对象的状态集中管理。
缺点:
系统设计更加复杂。
需要专门维护对象的外部状态。
适用场合:
需要大量细粒度对象。
这些对象的外部状态不多。
按照内部状态分成几个组,每一个组都仅用一个蝇量对象替代。
类结构图
示例代码:
package com.flyweight;
public abstract class Plant {
public Plant() {
}
public abstract void display(int xCoord, int yCoord, int age);
}
package com.flyweight;
public class Tree extends Plant {
@Override
public void display(int xCoord, int yCoord, int age) {
// TODO Auto-generated method stub
//System.out.println("Tree x");
}
}
package com.flyweight;
public class Grass extends Plant {
@Override
public void display(int xCoord, int yCoord, int age) {
// TODO Auto-generated method stub
//System.out.print("Grass x");
}
}
package com.flyweight;
import java.util.HashMap;
public class PlantFactory {
private HashMap plantMap = new HashMap();
public PlantFactory() {
}
public Plant getPlant(int type) {
if(!plantMap.containsKey(type)) {
switch(type) {
case 0:
plantMap.put(0, new Tree());
break;
case 1:
plantMap.put(1, new Grass());
break;
}
}
return plantMap.get(type);
}
}
package com.flyweight;
public class PlantManager {
private int length = 10000000;
private int[] xArray = new int[length],yArray = new int[length],
AgeArray = new int[length],typeArray = new int[length];
private PlantFactory mPlantFactory;
public PlantManager() {
mPlantFactory = new PlantFactory();
for(int i=0; i
xArray[i] = (int)(Math.random() * length);
yArray[i] = (int)(Math.random() * length);
AgeArray[i] = (int)(Math.random() * length)%5;
typeArray[i] = (int)(Math.random() * length)%2;
}
}
public void displayTree() {
for(int i=0; i
mPlantFactory.getPlant(typeArray[i]).display(xArray[i], yArray[i], AgeArray[i]);
}
}
}
package com.flyweight;
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
showMemInfo();
PlantManager mPlantManager;
mPlantManager = new PlantManager();
showMemInfo();
mPlantManager.displayTree();
showMemInfo();
}
public static void showMemInfo() {
//最大内存
long max = Runtime.getRuntime().maxMemory();
//分配内存
long total = Runtime.getRuntime().totalMemory();
//已分配内存中的剩余空间
long free = Runtime.getRuntime().freeMemory();
//已占用的内存
long used = total - free;
System.out.println("最大内存= " + max);
System.out.println("已分配内存= " + total);
System.out.println("已分配内存中的剩余空间= " + free);
System.out.println("已用内存= " + used);
System.out.println("时间= " + System.currentTimeMillis());
System.out.println("");
}
}
输出结果
最大内存= 259522560
已分配内存= 16252928
已分配内存中的剩余空间= 15536784
已用内存= 716144
时间= 1441355500069
最大内存= 259522560
已分配内存= 194347008
已分配内存中的剩余空间= 32881632
已用内存= 161465376
时间= 1441355502603
最大内存= 259522560
已分配内存= 194347008
已分配内存中的剩余空间= 32881632
已用内存= 161465376
时间= 1441355503120