文章出處
文章列表
使用頻率:★☆☆☆☆
一、什么是享元模式
大量細粒度對象共享復用
二、補充說明
可以節約內存空間,提高系統的性能;
一個對象有內部和外部兩種狀態,內部狀態是不變的,外部狀態是可變的,把一個對象分成內部狀態和外部狀態,然后通過共享內部狀態,達到節約內存空間的目的;
應用場景舉例:一個文檔中多次出現相同的圖片;一篇文章中出現了很多重復的字符串;圍棋的棋子(黑棋和白旗);
三、角色
抽象享元:一個接口或抽象類;
具體享元:內部狀態為其成員屬性,其實例為享元對象,可以共享;
享元工廠:生產享元對象,將具體享元對象存儲在一個享元池中,享元池一般設計為一個存儲“鍵值對”的集合;
客戶端:使用享元對象
四、例子,JAVA實現
一個共享字符串的例子
抽象享元
package com.pichen.dp.structuralpattern.flyweight; public interface IFlyweight { //id為外部狀態,不共享 public void setId(int id); }
具體享元
package com.pichen.dp.structuralpattern.flyweight; public class ShareStr implements IFlyweight{ //內部狀態str作為成員變量,共享的. private String str; public ShareStr(String str) { this.str = str; } //id為外部狀態,不共享 @Override public void setId(int id) { System.out.println("str: " + str + "id:" + id); } }
享元工廠
package com.pichen.dp.structuralpattern.flyweight; import java.util.HashMap; import java.util.Map; public class FlyweightFactory { private Map<String, Object> strMap = new HashMap<String, Object>(); public IFlyweight getInstance(String str){ IFlyweight fly = (IFlyweight) strMap.get(str); if(fly == null){ fly = new ShareStr(str); strMap.put(str, fly); } return fly; } }
客戶端
package com.pichen.dp.structuralpattern.flyweight; public class Main { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); ShareStr hello = (ShareStr) factory.getInstance("hello"); hello.setId(1); ShareStr hello2 = (ShareStr) factory.getInstance("hello"); hello.setId(2); ShareStr test = (ShareStr) factory.getInstance("test"); hello.setId(3); System.out.println(hello); System.out.println(hello2); System.out.println(hello.equals(hello2)); System.out.println(test); System.out.println(hello.equals(test)); } }
打印結果:
str: helloid:1 str: helloid:2 str: helloid:3 com.pichen.dp.structuralpattern.flyweight.ShareStr@feb48 com.pichen.dp.structuralpattern.flyweight.ShareStr@feb48 true com.pichen.dp.structuralpattern.flyweight.ShareStr@11ff436 false
文章列表
全站熱搜