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