Can anyone explain how does the following code of Flyweight pattern work:
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;
}
}
}
Thanks.
Basically what the code does is this:
When it is called it creates a temporary
BallFlyweight
with the given parameters.It then looks in the hashtable to see if an instance which is equal (has same hashcode) as this temporary instance already exists.
If it does then it returns the instance from the hashtable and allows the temporary instance to go out of scope and be garbage collected.
If it doesn't then it adds the temporary one to the hashtable (so next time the same instance is requested it will be found and returned) and returns it.
This will ensure that anyone using this function will always get the same instance when they pass the same values (assuming the function used to determine the hashcode works properly, and that the code is not accessed by multiple threads at the same time)