享元模式(英語:Flyweight Pattern)是一種軟體設計模式。它使用共享物件,用來儘可能減少記憶體使用量以及分享資訊給儘可能多的相似物件;它適合用於只是因重複而導致使用無法令人接受的大量記憶體的大量物件。通常物件中的部分狀態是可以分享。常見做法是把它們放在外部數據結構,當需要使用時再將它們傳遞給享元。
基本介紹
- 中文名:享元模式
- 外文名:Flyweight Pattern
- 性質:軟體設計模式
- 技術支持:共享技術
- 享元模式:共享技術的支持大量細粒度的對象
定義
結構
兩個狀態
UML結構圖
使用場景
示例
public enum FontEffect {BOLD, ITALIC, SUPERSCRIPT, SUBSCRIPT, STRIKETHROUGH}public final class FontData {/** * A weak hash map will drop unused references to FontData. * Values have to be wrapped in WeakReferences, * because value objects in weak hash map are held by strong references. */private static final WeakHashMap<FontData, WeakReference<FontData>> FLY_WEIGHT_DATA = new WeakHashMap<FontData, WeakReference<FontData>>();private final int pointSize;private final String fontFace;private final Color color;private final Set<FontEffect> effects;private FontData(int pointSize, String fontFace, Color color, EnumSet<FontEffect> effects){ this.pointSize = pointSize;this.fontFace = fontFace;this.color = color;this.effects = Collections.unmodifiableSet(effects);}public static FontData create(int pointSize, String fontFace, Color color, FontEffect... effects) { EnumSet<FontEffect> effectsSet = EnumSet.noneOf(FontEffect.class);for (FontEffect fontEffect : effects) {effectsSet.add(fontEffect);}// We are unconcerned with object creation cost, we are reducing overall memory consumption FontData data = new FontData(pointSize, fontFace, color, effectsSet);// Retrieve previously created instance with the given values if it (still) exists WeakReference<FontData> ref = FLY_WEIGHT_DATA.get(data);FontData result = (ref != null) ? ref.get() : null; // Store new font data instance if no matching instance existsif (result == null) {FLY_WEIGHT_DATA.put(data, new WeakReference<FontData> (data));result = data;}// return the single immutable copy with the given valuesreturn result;}@Overridepublic boolean equals(Object obj) {if (obj instanceof FontData) {if (obj == this) {return true;}FontData other = (FontData) obj;return other.pointSize == pointSize && other.fontFace.equals(fontFace) && other.color.equals(color) && other.effects.equals(effects);}return false;}@Overridepublic int hashCode() {return (pointSize * 37 + effects.hashCode() * 13) * fontFace.hashCode();}// Getters for the font data, but no setters. FontData is immutable.}