1、模式介紹:
????????享元模式是一種結構型設計模式,旨在通過共享對象來有效支持大量細粒度的對象。它通過將對象的狀態分為內部狀態(可共享)和外部狀態(不可共享)來減少內存消耗和提高性能。內部狀態存儲在享元對象內部,而外部狀態則由客戶端代碼管理和傳遞。
2、應用場景:
????????對象池:當程序中存在大量相似對象且不需要區分其具體身份時,可以使用享元模式。比如線程池、連接池等。
????????文本編輯器:對于每一個字符或者格式化文本片段,如果存在大量相同的文本片段,可以共享相同的內部狀態,減少內存消耗。
????????游戲開發:在游戲中,大量的角色或者粒子對象可能具有相同的外觀和行為,可以通過享元模式來節省資源。
????????字符串常量池:Java中的字符串常量池就是享元模式的一個實際應用,相同的字符串常量在內存中只存儲一份,多個字符串變量可以共享同一個常量。
3、優點:
????????減少內存消耗:通過共享相同的對象實例,減少內存使用。
????????提高性能:減少了創建對象的時間,特別是在對象頻繁被創建和銷毀的場景下。
4、缺點:
????????可能引入額外的復雜性:需要對內部狀態和外部狀態進行區分和管理,可能增加系統的復雜度。
????????需要合理劃分內部狀態和外部狀態:不正確的劃分可能導致系統的邏輯混亂。
5、代碼實現:
/*** 享元接口** @author FM_南風* @date 2024/6/27*/
public interface FlyweightInterface {//繪畫方法void draw();
}/*** 享元實現類** @author FM_南風* @date 2024/6/27*/
@Data
public class FlyweightClass implements FlyweightInterface{private final String color; // 顏色private int x, y, radius; // 坐標半徑public FlyweightClass(String color) {this.color = color;}@Overridepublic void draw() {System.out.println("享元實現類: 繪畫 [Color : " + color+ ", x : " + x + ", y :" + y + ", radius :" + radius);}
}/*** 享元工廠** @author FM_南風* @date 2024/6/27*/
public class FlyweightFactory {private static final Map<String, FlyweightInterface> flyweightMap = new HashMap<>();public static FlyweightInterface getCircle(String color) {FlyweightClass flyweightClass = (FlyweightClass) flyweightMap.get(color);if (flyweightClass == null) {flyweightClass = new FlyweightClass(color);flyweightMap.put(color, flyweightClass);System.out.println("開始創作: " + color);}return flyweightClass;}
}/*** 應用** @author FM_南風* @date 2024/6/27*/
public class FlyweightClient {private static final String[] colors = {"紅", "綠", "藍"};public static void main(String[] args) {for (int i = 0; i < 20; ++i) {FlyweightClass circle = (FlyweightClass) FlyweightFactory.getCircle(getRandomColor());circle.setX(getRandomX());circle.setY(getRandomY());circle.setRadius(100);circle.draw();}}private static String getRandomColor() {return colors[(int) (Math.random() * colors.length)];}private static int getRandomX() {return (int) (Math.random() * 100);}private static int getRandomY() {return (int) (Math.random() * 100);}
}
6、結果展示:
7、代碼示例說明:
在這個示例中:FlyweightClass類作為具體享元類,顏色(內部狀態)color?是享元的一部分,而 x、y、raidus則是外部狀態。
FlyweightFactory?類作為享元工廠,負責管理和提供享元對象。享元對象在首次創建時存儲在 flyweightMap?中,以便于后續共享使用。
FlyweightClient類作為客戶端代碼,演示如何使用享元模式來創建和繪制多個圓形對象,共享相同的顏色。
通過享元模式,可以看到多個具有相同顏色的圓形對象共享同一個 FlyweightClass 實例,從而減少了對象的創建和內存消耗。