1. 定义
运用共享技术有效地支持大量的细粒度对象的复用。
2. 角色
- Flyweight:抽象蝇量类
- ConcreteFlyweight:具体蝇量类
- FlyweightFactory:蝇量工厂
3. 特点
- 优点:减少内存中对象的数量,使得相同或相似的对象在内存中可以集中管理。
- 缺点:该模式需要分离出内部状态和外部状态,使程序的逻辑变得复杂。
4. 示例
公园里有许多树和草,需要展示它们的坐标。如果为每一棵树或草都创建一个对象,会耗费许多内存,因此仅创建一个树的对象和一个草的对象,通过将它们的坐标传入来展示。
Plant:
public abstract class Plant {
public Plant() {}
public abstract void display(int x, int y);
}
具体蝇量类(即树和草):
// Tree
public class Tree extends Plant {
@Override
public void display(int x, int y) {
System.out.println("树:" + x + ", " + y);
}
}
// Grass
public class Grass extends Plant {
@Override
public void display(int x, int y) {
System.out.println("草:" + x + ", " + y);
}
}
PlantFactory:
import java.util.HashMap;
import java.util.Map;
public class PlantFactory {
private Map<Integer, Plant> plants;
public PlantFactory() {
plants = new HashMap<>();
}
public Plant getPlant(int type){
if (!plants.containsKey(type)) {
if (type == 1) {
Plant tree = new Tree();
plants.put(1, tree);
return tree;
} else if (type == 0) {
Plant grass = new Grass();
plants.put(0, grass);
return grass;
}
}
return plants.get(type);
}
}
测试类:
public class TestFlyweight {
public static void main(String[] args) {
int[] xArrays = new int[5];
int[] yArrays = new int[5];
int[] typeArrays = new int[5];
for (int i = 0; i < 5; i++) {
xArrays[i] = (int) (Math.random() * 5);
yArrays[i] = (int) (Math.random() * 5);
typeArrays[i] = (int) (Math.random() * 5) % 2;
}
PlantFactory plantFactory = new PlantFactory();
for (int i = 0; i < 5; i++) {
plantFactory.getPlant(typeArrays[i]).display(xArrays[i], yArrays[i]);
}
}
}
// 输出
// 树:3, 1
// 树:0, 2
// 草:3, 2
// 树:0, 1
// 树:4, 1
参考:
1. 《Head First 设计模式》
2. 《图说设计模式》https://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/flyweight.html