Design patterns 飞锤图案
有人能解释一下Flyweight模式的以下代码是如何工作的吗:Design patterns 飞锤图案,design-patterns,flyweight-pattern,Design Patterns,Flyweight Pattern,有人能解释一下Flyweight模式的以下代码是如何工作的吗: public class FlyweightFactory { Hashtable hash = new Hashtable(); public BallFlyweight getFlyweight(int r, Color col, Container c, AStrategy a) { BallFlyweight tempFlyweight = new BallFlyweight(r,col,c,
public class FlyweightFactory {
Hashtable hash = new Hashtable();
public BallFlyweight getFlyweight(int r, Color col, Container c, AStrategy a) {
BallFlyweight tempFlyweight = new BallFlyweight(r,col,c,a),
hashFlyweight = ((BallFlyweight)hash.get(tempFlyweight));
if(hashFlyweight != null)
return hashFlyweight;
else {
hash.put(tempFlyweight,tempFlyweight);
return tempFlyweight;
}
}
}
谢谢。代码的基本功能是: 调用时,它将使用给定的参数创建一个临时的
BallFlyweight
然后在哈希表中查看是否已经存在与此临时实例相等的实例(具有相同的哈希代码)
如果它这样做了,那么它将从哈希表返回实例,并允许临时实例超出范围并被垃圾收集
如果没有,则将临时实例添加到哈希表中(因此下次请求同一实例时将找到并返回该实例)并返回它
这将确保使用此函数的任何人在传递相同的值时始终获得相同的实例(假设用于确定哈希代码的函数工作正常,并且代码不会同时被多个线程访问)Flyweight使用共享功能,因此大量对象可以高效地拥有相同的数据或功能。flyweight用于规范化数据在内存中的保存方式。在大多数情况下,跨大量对象共享的组件是不可变的
我认为上面的代码实际上是一个mutton()请花点时间来正确格式化您的问题。