蝇量模式(Flyweight Pattern)

蝇量模式:让某个类的一个实例能用来提供许多“虚拟实例”。

在有大量对象时,有可能造成内存溢出,把其*同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重复创建。(JAVA中的String,如果没有则创建一个字符串保存在字符串常量池里,否则直接返回)

类图:

蝇量模式(Flyweight Pattern)

public interface Planet {
public abstract void display(int x, int y);
} public class Tree implements Planet {
private int x;
private int y;
private String height; public int getX() {
return x;
} public void setX(int x) {
this.x = x;
} public int getY() {
return y;
} public void setY(int y) {
this.y = y;
} public Tree(String height) {
this.height = height;
} @Override
public void display(int x, int y) {
System.out.println(height + "Tree in x=" + x + " y=" + y);
} } public class PlanetFactory {
private static final HashMap<String, Planet> planetMap = new HashMap<String, Planet>(); public static Planet getTree(String height) {
Tree tree = (Tree) planetMap.get(height);
if(tree == null) {
tree = new Tree(height);
planetMap.put(height, tree);
System.out.println("Creating tree of height : " + height);//只有在map中找不到对象才创建一个,将这句话打印出来
}
return tree;
}
} public class Client {
private static final String height[] = {"Tall", "Medium", "Short"};
private static String getRandomHeight() {
return height[(int) (Math.random() * height.length)];
}
private static int getRandomX() {
return (int) (Math.random() * );
}
private static int getRandomY() {
return (int) (Math.random() * );
}
public static void main(String[] args) {
for(int i = ; i < ; i++) {
Tree tree = (Tree) PlanetFactory.getTree(getRandomHeight());
tree.display(getRandomX(), getRandomY());
} } }

某次测试结果:

Creating tree of height : Tall
TallTree in x=57 y=88
TallTree in x=10 y=24
Creating tree of height : Short
ShortTree in x=8 y=61
ShortTree in x=92 y=27
ShortTree in x=58 y=73
TallTree in x=22 y=25
ShortTree in x=95 y=3
Creating tree of height : Medium
MediumTree in x=0 y=1
MediumTree in x=95 y=38
MediumTree in x=35 y=56
TallTree in x=67 y=5
MediumTree in x=35 y=47
ShortTree in x=37 y=32
ShortTree in x=40 y=94
MediumTree in x=43 y=11
MediumTree in x=4 y=94
ShortTree in x=68 y=70
ShortTree in x=62 y=56
ShortTree in x=13 y=69
MediumTree in x=21 y=49

上一篇:辛星跟您玩转vim第一节之vim的下载与三种模式


下一篇:Android 使用httpClient POST 模拟发送 multipart表单内容