10.18

liuxuechao發表於2024-11-20

享元模式

享元模式(Flyweight Pattern)是一種結構型設計模式,它透過共享物件來減少記憶體使用和提高效能。享元模式適用於需要建立大量相似物件的情況,透過共享這些物件的內部狀態,可以顯著減少物件的數量。

下面是一個簡單的Java程式碼示例,演示了享元模式的實現:

import java.util.HashMap;
import java.util.Map;

// 共享的抽象享元類
interface Flyweight {
    void operation();
}

// 具體享元類
class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;

    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation() {
        System.out.println("ConcreteFlyweight: " + intrinsicState);
    }
}

// 享元工廠類
class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        if (flyweights.containsKey(key)) {
            return flyweights.get(key);
        } else {
            Flyweight flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
            return flyweight;
        }
    }
}

// 客戶端程式碼
public class FlyweightPatternExample {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        
        Flyweight flyweight1 = factory.getFlyweight("A");
        flyweight1.operation();
        
        Flyweight flyweight2 = factory.getFlyweight("B");
        flyweight2.operation();
        
        Flyweight flyweight3 = factory.getFlyweight("A");
        flyweight3.operation();
    }
}

在上述示例中,我們定義了一個共享的抽象享元類 Flyweight,其中包含一個 operation() 方法。

然後,我們實現了具體享元類 ConcreteFlyweight,它實現了 Flyweight 介面,並持有一個內部狀態 intrinsicState

接著,我們建立了享元工廠類 FlyweightFactory,它維護了一個享元物件的快取池 flyweights。在 getFlyweight() 方法中,我們透過檢查快取池是否存在對應的享元物件,如果存在則直接返回,否則建立新的享元物件並新增到快取池中。

在客戶端程式碼中,我們例項化了享元工廠物件 FlyweightFactory,並透過呼叫 getFlyweight() 方法獲取享元物件。在多次獲取同一個內部狀態的享元物件時,實際上是獲取的同一個物件例項。

享元模式的關鍵思想是共享物件的內部狀態,以減少物件的數量。透過共享相同的內部狀態,可以節省記憶體空間,並提高系統的效能。需要注意的是,享元模式將物件的內部狀態與外部狀態分離,內部狀態是可以共享的,而外部狀態是變化的,每個物件都需要獨立維護。