享元模式(Flyweigh),運用共享技術有效地支持大量細粒度的對象。
?
package flyweight;//可以接受并作用于外部狀態 public abstract class Flyweight {public abstract void operation(int extrinsicState);}
?
package flyweight;//為內部狀態增加存儲空間 public class ConcreteFlyweight extends Flyweight{@Overridepublic void operation(int extrinsicState) {System.out.println("ConcreteFlyweight"+extrinsicState);}}
?
package flyweight;//不需要共享的子類 public class UnsharedConcreteFlyweight extends Flyweight {@Overridepublic void operation(int extrinsicState) {System.out.println("UnsharedConcreteFlyweight"+extrinsicState);}}
?
package flyweight;import java.util.HashMap;public class FlyweightFactory {private HashMap<String, Flyweight> flyweightMap=new HashMap<String, Flyweight>();public FlyweightFactory() {flyweightMap.put("X", new ConcreteFlyweight());flyweightMap.put("Y", new ConcreteFlyweight());flyweightMap.put("Z", new ConcreteFlyweight());}public Flyweight getFlyweightMap(String key) {return flyweightMap.get(key);}public static void main(String[] args) {int extrinsicState=22;FlyweightFactory flyweightFactory=new FlyweightFactory();Flyweight flyweight=flyweightFactory.getFlyweightMap("X");flyweight.operation(--extrinsicState);Flyweight flyweight2=flyweightFactory.getFlyweightMap("Y");flyweight.operation(--extrinsicState);Flyweight flyweight3=flyweightFactory.getFlyweightMap("Z");flyweight.operation(--extrinsicState);UnsharedConcreteFlyweight unsharedConcreteFlyweight=new UnsharedConcreteFlyweight();unsharedConcreteFlyweight.operation(--extrinsicState);}}
?
享元模式可以避免大量非常相似類的開銷。在程序設計中,有時需要生成大量細粒度的類實例來表示數據。如果能發現這些實例除了幾個參數外基本上都是相同的,有時就能夠大幅度地減少需要實例化的類的數量,如果能把那些參數移到類實例的外面,在方法調用時將它們傳遞進來,就可以通過共享大幅度地減少單個實例的數目。
?