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