當系統中存在大量相似對象時,每個對象都需要占用一定的內存空間,如果這些對象的大部分屬性是相同的,那么頻繁創建這些對象會導致內存消耗過大。享元模式將這些相同部分抽取出來作為共享的內部狀態,在需要時進行共享,從而減少內存占用。
享元模式(Flyweight Pattern)是一種結構型設計模式,旨在通過共享對象來最大化內存利用和性能提升,享元模式嘗試重用現有的同類對象,如果未找到匹配的對象,則創建新對象。
享元模式在對象池中的使用是一種常見的場景,通過對象池管理和復用對象實例,可以提高系統性能和資源利用率。對象池通常用于緩存、連接池等場景,其中對象的創建成本較高或者頻繁創建銷毀會影響性能時,對象池就顯得尤為重要。
在 Java 中,String 類的 intern() 方法是享元模式的一個應用。intern() 方法返回字符串對象的規范化表示形式,即返回字符串池中與調用字符串等效的字符串。如果字符串池中已經存在等效的字符串,則返回該字符串;否則,將此字符串添加到字符串池中,并返回新的字符串引用。
下面是一個示例代碼,演示了 String 類的 intern() 方法的應用:
public class StringInternExample { public static void main(String[] args) { String str1 = "hello"; String str2 = new String("hello"); String str3 = str2.intern(); System.out.println("str1 == str2: " + (str1 == str2)); // false System.out.println("str1 == str3: " + (str1 == str3)); // true }}
在上述示例中,str1 和 str2 是兩個不同的字符串對象,盡管它們的值相同,但由于 str2 使用了 new String() 構造方法創建,在堆內存中會生成一個新的對象。而通過調用 intern() 方法后,str3 返回的是字符串池中已存在的字符串對象,因此 str1 和 str3 指向的是同一個對象,所以輸出結果為 "str1 == str3: true"。這就是 intern() 方法的享元模式應用,避免了重復創建相同的字符串對象,節省了內存空間。
享元模式包含以下幾個角色:
在享元模式中,核心在于區分內部狀態和外部狀態。內部狀態是可以共享的部分,而外部狀態是對象的非共享部分。
通過區分內部狀態和外部狀態,享元模式實現了將對象的共享部分和變化部分分離的目的,有效地減少了系統中重復對象的數量,提高了系統的性能和資源利用率。內部狀態是享元對象本身的屬性,而外部狀態則是根據具體情況動態變化的參數。
實現步驟和示例代碼如下:
1.首先定義抽象享元角色。
public abstract class Flyweight { //內部狀態 private String intrinsic; //外部狀態 protected final String extrinsic; //要求享元角色必須接受外部狀態 public Flyweight(String extrinsic){ this.extrinsic = extrinsic; } //定義業務操作 public abstract void operate(); //內部狀態的getter/setter public String getIntrinsic() { return intrinsic; } public void setIntrinsic(String intrinsic) { this.intrinsic = intrinsic; }}
抽象享元角色一般為抽象類,它是描述一類事物的方法。
2.具體享元角色。
public class ConcreteFlyweight1 extends Flyweight{ //接受外部狀態 public ConcreteFlyweight1(String extrinsic){ super(extrinsic); } //根據外部狀態進行邏輯處理 public void operate(){ //業務邏輯 }}
public class ConcreteFlyweight2 extends Flyweight{ //接受外部狀態 public ConcreteFlyweight2(String extrinsic){ super(extrinsic); } //根據外部狀態進行邏輯處理 public void operate(){ //業務邏輯 }}
具體享元角色實現自己的業務邏輯,然后接收外部狀態,以便內部業務邏輯對外部狀態的依賴。
3.享元工廠。
public class FlyweightFactory { //定義一個池容器 private static Map<String, Flyweight> pool = new HashMap<>(); //享元工廠 public static Flyweight getFlyweight(String extrinsic) { //需要返回的對象 Flyweight flyweight; //在池中沒有該對象 if (pool.containsKey(extrinsic)) { flyweight = pool.get(extrinsic); } else { //根據外部狀態創建享元對象 flyweight = new ConcreteFlyweight1(extrinsic); //放置到池中 pool.put(extrinsic, flyweight); } return flyweight; }}
4.客戶端調用
public static void main(String[] args) { Flyweight flyweight1 = FlyweightFactory.getFlyweight("hello world"); System.out.println(flyweight1.hashCode()); Flyweight flyweight2 = FlyweightFactory.getFlyweight("hello world"); System.out.println(flyweight2.hashCode()); } Output: 1705736037 1705736037
可以發現對象打印的 hashCode 一致,說明對象得到了復用。
Tips:外部狀態最好以Java的基本類型作為標志,如String、int等,可以大幅地提升效率。如果使用自己編寫的類作為外部狀態,則必須覆寫equals方法和hashCode方法,否則會出現通過鍵值搜索失敗的情況,例如map.get(object)、map.contains(object)等會返回失敗的結果。
享元模式在多線程環境下可能存在線程安全問題,主要原因是享元對象的內部狀態和外部狀態被多個線程共享和修改,可能導致數據競爭和不一致性。具體來說,如果多個線程同時嘗試修改同一個享元對象的外部狀態,就會引發線程安全問題。
下面是示例代碼:
public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(() -> { Flyweight flyweight1 = FlyweightFactory.getFlyweight("hello world"); Flyweight flyweight2 = FlyweightFactory.getFlyweight("hello world"); System.out.println(flyweight1 == flyweight2); }).start(); } }Output:truefalsetruetruetruetruetruetruetruetrue
這段代碼展示了多線程環境下使用享元模式的示例。在 main 方法中,通過循環創建了 10 個線程,在每個線程中嘗試獲取表示 "hello world" 的享元對象,并比較兩個獲取的對象是否相等。
可以觀察到輸出中存在 false,說明對象不一樣了,存在線程安全問題。
要想實現線程安全,需要對享元工廠類稍加改造,代碼如下:
public class FlyweightFactory { //定義一個池容器 private static Map<String, Flyweight> pool = new ConcurrentHashMap<>(); //享元工廠 public static synchronized Flyweight getFlyweight(String extrinsic) { Flyweight flyweight = pool.putIfAbsent(extrinsic, new ConcreteFlyweight1(extrinsic)); if (flyweight == null) { return pool.get(extrinsic); } return flyweight; }}
這樣就解決了線程安全問題,不過性能上會有所降低,在需要的地方考慮一下線程安全即可,在大部分的場景下都不用考慮。
享元模式通過共享相似對象來減少內存消耗,提高系統性能。它適用于存在大量相似對象且造成內存浪費的場景,但需要注意對內部狀態和外部狀態的管理。合理應用享元模式可以有效優化系統架構,提升性能。
優點
缺點
本文鏈接:http://www.www897cc.com/showinfo-26-75345-0.html一文搞懂設計模式—享元模式
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com