第93章
小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的内部设计上。”