定義:運用共享技術有效的支持大量細粒度的對象
java
類型:結構型模式 git
順口溜:適裝橋組享代外github
package com.amosli.dp.structural.flyweight; public abstract class Flyweight { abstract void operation(int extrinsicstate); } package com.amosli.dp.structural.flyweight; public class ConcreteFlyweight extends Flyweight { @Override void operation(int extrinsicstate) { System.out.println(this.getClass().getName() + extrinsicstate); } } package com.amosli.dp.structural.flyweight; public class ConcreteFlyweight extends Flyweight { @Override void operation(int extrinsicstate) { System.out.println(this.getClass().getName() + extrinsicstate); } } package com.amosli.dp.structural.flyweight; import java.util.HashMap; public class FlyweightFactory { private HashMap<String, Flyweight> flys = new HashMap<String, Flyweight>(); public FlyweightFactory() { flys.put("x", new ConcreteFlyweight()); flys.put("y", new ConcreteFlyweight()); flys.put("z", new ConcreteFlyweight()); } public Flyweight getFlyweight(String key) { return flys.get(key); } }
享元模式通常是給出本地內存資源節省的一個方案,並不適合互聯網上的分佈式應用的狀況,不過享元模式對於排他性的要求資源的控制,是個不錯的選擇的。分佈式
本系列文章源碼地址,https://github.com/amosli/dp 歡迎Fork & Star !!ide