」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 蠅量級

蠅量級

發佈於2024-11-06
瀏覽:973

Flyweight

結構模式之一旨在透過與相似物件共享盡可能多的資料來減少記憶體使用。
在處理大量相似物件時特別有用,為每個物件建立一個新實例在記憶體消耗方面會非常昂貴。
關鍵概念:
內在狀態:多個物件之間共享的狀態獨立於上下文,並且在不同物件之間保持相同。
外部狀態:每個物件唯一的、從客戶端傳遞的狀態。此狀態可能會有所不同,並且不會儲存在 Flyweight 物件中

主要參與者:

Flyweight:Flyweight物件接收外部狀態並使用它的介面。
ConcreteFlyweight:實作 Flyweight 並儲存內在狀態。
FlyweightFactory:管理Flyweight物件並確保介面共享,如果存在則傳回一個現有的Flyweight。

Client(如 Main 類別):維護 Flyweight 的引用,並在需要與 Flyweight 物件互動時提供外部狀態。

我們以角色的 Flyweight 物件為例
假設我們有一個文字編輯器需要渲染大量文字。每個字元都可以表示為一個對象,但是為每個字元都有一個單獨的對象會浪費大量記憶體。相反,我們可以使用 Flyweights 來共享代表每個字母的字元對象,並儲存外部狀態,例如外部的位置或格式

蠅量級

public interface Flyweight {
    public void display(int x, int y);//x, y are the extrinsic state of the Flyweight object
}

混凝土享元

public class CharacterFlyweight implements Flyweight {
    private char ch;
    public CharacterFlyweight(char c){
        this.ch  = c;
    }
    @Override
    public void display(int x ,int y){
        System.out.println("[drawing character: " this.ch " at co-ordinates:(" x "," y ")]");
    }

}

FlyweightFactory

public class FlyweightFactory {
    private static HashMap flyweights = new HashMap();
    public static Flyweight getFlyweight(char c){
        Flyweight flyweight = flyweights.getOrDefault(c,null);
        if(null==flyweight){
            flyweight = new CharacterFlyweight(c);
            flyweights.put(c,flyweight);
        }
        return flyweight;
    }
}

主要的

public class Main {
    public static void main(String args[]){
        Flyweight flyweight1 = FlyweightFactory.getFlyweight('a');
        Flyweight flyweight2 = FlyweightFactory.getFlyweight('b');
        Flyweight flyweight3 = FlyweightFactory.getFlyweight('a');// will use the same object that is referenced by flyweight1

        flyweight1.display(1, 2);//'a' displayed at 1,2
        flyweight2.display(3, 4);//'b' displayed at 3,4
        flyweight3.display(5, 7); // 'a'(shared) displayed at 5,7
    }
}

輸出:

[drawing character: a at co-ordinates:(1,2)]
[drawing character: b at co-ordinates:(3,4)]
[drawing character: a at co-ordinates:(5,7)]

要點

  • 記憶體效率:透過共享物件減少記憶體使用,特別是當內在狀態很大或物件很多時。
  • 效能改進:減少創建的物件數量,可以提高應用程式在管理大量物件時的效能。

缺點
複雜性:此模式會增加程式碼的複雜性,特別是在分別管理外部和內部狀態時。
開銷:如果要共享的物件很少,享元模式可能會引入不必要的複雜性,而不會顯著節省記憶體。

版本聲明 本文轉載於:https://dev.to/prashantrmishra/flyweight-3k4b?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3