目录
上述代码 GitHub 地址:https://github.com/baicun/designPatterns
蝇量模式(享元模式):
通过共享的方式高效地支持大量细粒度的对象。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。享元模式结构较为复杂,一般结合工厂模式一起使用
蝇量模式优点:
1、减少运行时的对象实例个数,节省创建开销和内存。
2、将许多“虚拟”对象的状态集中管理。从而使得享元对象可以在不同的环境中被共享。
蝇量模式缺点:
系统设计更加复杂,需要分离出内部状态和外部状态。
蝇量模式应用:
String、Integer 变量放到字符串常量池。
蝇量模式实例:
类图:
示例:
景观设计软件:我要设计一出园林景观,需要使用大量的树、草等,从一般角度来看,需要一个创建一个,这样可能会创建大量的实例,为了解决这个问题,我们需要使用蝇量模式,区分内部类和外部类,将草、树抽象成一个植物类,二它们本身作为具体类,它们的状态统一由外部状态类控制,通过工厂类创建获取。
代码:
抽象享元类-植物
public abstract class Plant {
public Plant() {
}
public abstract void display(int xCoord, int yCoord, int age);
}
具体享元类-树
public class Tree extends Plant {
@Override
public void display(int xCoord, int yCoord, int age) {
// TODO Auto-generated method stub
// System.out.print("Tree x");
}
}
具体享元类-草坪
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");
}
}
享元工厂类
public class PlantFactory {
//定义一个HashMap用于存储享元对象,实现享元池
private HashMap<Integer, Plant> plantMap = new HashMap<Integer, Plant>();
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);
}
}
集中管理类
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 < length; 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 displayTrees() {
for (int i = 0; i < length; i++) {
mPlantFactory.getPlant(typeArray[i]).display(xArray[i], yArray[i], AgeArray[i]);
}
}
}
测试类:
public class MainTest {
public static void main(String[] args) {
showMemInfo();
PlantManager mPlantManager;
mPlantManager = new PlantManager();
showMemInfo();
mPlantManager.displayTrees();
showMemInfo();
}
public static void showMemInfo() {
// 已分配内存中的剩余空间 :
long free = Runtime.getRuntime().freeMemory();
// 分配内存:
long total = Runtime.getRuntime().totalMemory();
// 最大内存:
long max = Runtime.getRuntime().maxMemory();
// 已占用的内存:
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("");
}
}
上述代码 GitHub 地址:https://github.com/baicun/designPatterns