當以下情況出現時,使用 Flyweight 模式:
Flyweight: 聲明一個接口,通過該接口享元可以接收並對外部狀態 (extrinsic states) 進行操作
ConcreteFlyweight: 實現享元接口並存儲內部狀態 (intrinsic state)
UnsharedConcreteFlyweight: 並非所有 Flyweight 子類都需要共享
FlyweightFactory: 創建和管理 Flyweight 對象
Client: 維護對 Flyweight 的引用,並計算或存儲 Flyweight 的外部狀態
Intrinsic State (內部狀態)
特點
例子: 在森林模擬中,樹的種類(如松樹、橡樹等)可以作為內部狀態
Extrinsic State (外部狀態)
特點
例子: 在森林模擬中,樹的位置(x, y 座標)可以作為外部狀態
總結
// Flyweight Interface
class LED {
public:
virtual void display(int brightness) = 0;
};
// Concrete Flyweight
class ConcreteLED : public LED {
private:
std::string color;
public:
ConcreteLED(std::string color) : color(color) {}
void display(int brightness) override {
std::cout << "Displaying " << color << " LED with brightness: " << brightness << std::endl;
}
};
// Flyweight Factory
class LEDFactory {
private:
std::map<std::string, LED*> ledMap;
public:
LED* getLED(std::string color) {
// map 原先不存在這個顏色的 LED 的話,new 1 個 ConcreteLED 存進去 map
if (ledMap.find(color) == ledMap.end()) {
ledMap[color] = new ConcreteLED(color);
}
return ledMap[color];
}
};
int main() {
LEDFactory factory;
// Client code
LED* redLED = factory.getLED("Red");
redLED->display(10);
LED* greenLED = factory.getLED("Green");
greenLED->display(20);
LED* anotherRedLED = factory.getLED("Red");
anotherRedLED->display(15);
}
Composite Pattern (組合模式): Often used with Flyweight for a hierarchical structure
Factory Method Pattern (工廠方法模式): Useful for creating flyweight objects