享元模式(Flyweight):能夠避免大量很是類似類的開銷。在程序設計中,有時須要生成大量細粒度的類實例來表示數據。若是能發現這些事例除了幾個參數外基本相同的,有時就可以大幅度的減小須要實例化的類的數量。java
若是能把哪些參數移到類事例的外面,在方法調用的時候將他們傳遞進來,就能夠經過共享大幅度的減小單個實例的數目ide
package com.fumeck.design.flyweight; public abstract class FlyWeight { private String name; public FlyWeight(String name) { this.name = name; } public abstract void excute(); }
package com.fumeck.design.flyweight; public class ConcreteFlyWeight extends FlyWeight{ public ConcreteFlyWeight(String name) { super(name); } @Override public void excute() { //具體事件 } }
package com.fumeck.design.flyweight; import java.util.HashMap; import java.util.Map; public class FlyWeightFactory { private Map<String, FlyWeight> map = new HashMap(); public FlyWeight getFlyWeight(String name) { FlyWeight flyWeight = map.get(name); if (flyWeight != null) { return map.get(name); } else { flyWeight = new ConcreteFlyWeight(name); map.put("name", flyWeight); return flyWeight; } } }