Flyweight pattern

297 views Asked by At

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.

2

There are 2 answers

0
Sam Holder On

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)

0
andrew pate On

Flyweight uses sharing so large numbers of objects can possess the same data or feature efficiently. A flyweight serves as a normalization of how data is held in memory. In most cases components that get shared across the large number of objects are immutable.

I would argue the code above is really a mutiton (https://en.wikipedia.org/wiki/Multiton_pattern)