享元模式:運用共享技術有效地支持大量細粒度的對象
如果一個應用程序使用了大量的對象,而大量的這些對象造成了很大的存儲開銷時就應該考慮使用;還有對象的大多數狀態可以外部狀態,如果刪除對象的外部狀態,那麼可以用相對較少的共享對象取代很多組對象。
UML:
JAVA:
public class FlyWeightTest {
public static void main(String[] args) {
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.getFlyweight("X");
fx.operation(--extrinsicstate);
Flyweight fy = f.getFlyweight("Y");
fx.operation(--extrinsicstate);
UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
uf.operation(--extrinsicstate);
}
}
class FlyweightFactory{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory(){
flyweights.put("X",new ConcreteFlyweight());
flyweights.put("Y",new ConcreteFlyweight());
flyweights.put("Z",new ConcreteFlyweight());
}
public Flyweight getFlyweight(String key){
return (Flyweight) flyweights.get(key);
}
}
abstract class Flyweight{
public abstract void operation(int extrinsicstate);
}
class ConcreteFlyweight extends Flyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("具體實現Flyweight:"+extrinsicstate);
}
}
//不需要共享的子類
class UnsharedConcreteFlyweight extends Flyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("不共享的 具體實現Flyweight:"+extrinsicstate);
}
}