小A:“如何去使用享元模式?”
大B:“我们先从Flyweight抽象接口开始。”
public interface Flyweight
{
public void operation(ExtrinsicState state);
}
//用于本模式的抽象数据类型(自行设计)
public interface ExtrinsicState{}
大B:“接下来我们讲的是接口的具体实现(ConcreteFlyweight),并为内部状态增加内存空间,ConcreteFlyweight必须是可共享的,它保存的任何状态都必须是内部(intrinsic),也就是说,ConcreteFlyweight必须和它的应用环境场合无关。”
public class ConcreteFlyweight implements Flyweight{
private IntrinsicState state;
public void operation(ExtrinsicState state)
{
//具体操作
}
}
小A:“是不是所有的Flyweight具体实现子类都需要被共享?”
大B:“当然并不是所有的Flyweight具体实现子类都需要被共享的,所以还有另外一种不共享的ConcreteFlyweight。”
public class UnsharedConcreteFlyweight implements Flyweight{
public void operation(ExtrinsicState state){}
}
大B:“Flyweight factory负责维护一个Flyweight池(存放内部状态),当客户端请求一个共享Flyweight时,这个factory首先搜索池中是否已经有可适用的,如果有,factory只是简单返回送出这个对象,否则,创建一个新的对象,加入到池中,再返回送出这个对象池。”
public class FlyweightFactory{
//Flyweight pool
private Hashtable flyweights=new Hashtable();
public Flyweight getFlyweight(Object key){
Flyweight flyweight=(Flyweight)flyweights。get(key);
if(flyweight……null){
//产生新的。
flyweight=new ConcreteFlyweight();
flyweights。put(key,flyweight);
}
return flyweight;
}
}
大B:“到现在为止,Flyweight模式的基本框架已经就绪,我们就来看看如何调用。”
FlyweightFactory factory=new FlyweightFactory();
Flyweight fly1=factory。getFlyweight(“Fred”);
Flyweight fly2=factory。getFlyweight(“Wilma”);
……
大B:“从调用上看,好象是个纯粹的Factory使用,但奥妙就在于Factory的内部设计上。”