1. 程式人生 > >設計模式(9)—— 結構型 ——享元(Flyweight)

設計模式(9)—— 結構型 ——享元(Flyweight)

介紹

  • 定義:提供了減少物件數量從而改善應用所需的物件結構的方式
  • 說明:運用共享技術有效地支援大量細粒度的物件
  • 型別:結構型
  • 適用場景:
    • 常常應用於系統底層的開發,以便解決系統的效能問題(Java中String的實現,資料庫的連線池)
    • 系統有大量相似物件,需要快取池的場景。
  • 優點:
    • 減少物件的建立,降低記憶體中的物件數量,降低系統的記憶體,提高效率。
    • 減少記憶體之外的其它資源佔用。
  • 缺點
    • 關注內/外部狀態,關注執行緒安全問題
    • 系統,程式的邏輯複雜化
  • 擴充套件
    • 內部狀態
    • 外部狀態
  • 相關的設計模式
    • 享元模式和代理模式
    • 享元模式和單例模式

程式碼實現

例項程式碼看他人的部落格:點選

再看JDK中是怎樣運用的,我們首先關注這段測試程式碼:

Integer a = Integer.valueOf(25);
Integer b = 25;

Integer c = Integer.valueOf(1000);
Integer d = 1000;

System.out.
println("a==b:"+(a==b)); System.out.println("c==d:"+(c==d));

檢視輸出結果:

a==b:true
c==d:false

我們檢視valueOf原始碼,大致能推斷出問題所在(注意一定要看註釋啦):

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }

注意到下面的註釋說明:方法總是會快取-128~127範圍內的值(其中包含範圍邊界),可能會快取在此範圍外的值

     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.

於是也就很容易理解上面的程式碼了。
i >= IntegerCache.low && i <= IntegerCache.high先判斷值是否在快取中,如果在,那麼直接從快取中取,那麼必然會共享一個記憶體地址。如果不在快取中,此時才new一個新物件。