Imagine that you are developing some gaming software. Your write Web client and on each of response you are parsing entire XML to get your game Units. You have some set of types of Units, for example 50 different animals, but when you parse your XML you can get dozens of instances of the same Unit and few dozens of instances of other Unit.
If User of the game is very passionate gamer, he could send requests very frequently. In this case your application will be creating dozens of instances for each of the Unit. But, your units have some static descriptions. For example, Dragon has Attack, initial Health level, and also you need to keep image of the dragon in the object of Dragon.

This all lead to intensive and not efficient memory usage. How could you share common information for all types of Units without creating instances for each individual Unit?

FLYWEIGHT

1) Simplest way with creating objects each time.

We have base class Unit:
 

public class Unit {
    protected String name;
    protected int health;
    protected String picture;
   
    public void setName(String name) {
    this.name = name;
    }
    public String getName() {
    return name;
    }
    public void setHealth(int health) {
    this.health = health;
    }
    public int getHealth() {
    return health;
    }
    public void setPicture(String picture) {
    this.picture = picture;
    }
    public String getPicture() {
    return picture;
    }
}

 
And two derived – Dog and Dragon. To make those objects more weightfull I added to them picture. In my case that is only very long string.

public class Dog extends Unit{
    public Dog(){
        name = “dog”;
        health = 30;
       
        for(int i = 0; i < 100; ++i)
            picture += “I
don’t want to load actuall image, but if we will be creating a lot of
strings on each of the Unit this could be very resrouce taking
operation.”
;
    }
}


And our parser executes code which looks like:

public class Parser {
    public ArrayList<Unit> parse(){
   
    ArrayList<Unit> result = new ArrayList<Unit>();

    for(int i = 0; i < 150; ++i)
        result.add(new Dragon());
   
    for(int i = 0; i < 600; ++i)
        result.add(new Dog());
   
    System.out.println(“Dogs and Dragons are parsed.”);
   
    return result;
    }
}

We want to create only 150 Dragons and 600 Dogs and this takes 28 Mb of memory.

2) How does FlyWeight work?

Lets introduce UnitsFactory. Responsibility of this factory is to manage creation of the concrete flyweight objects (Dogs and Dragons). It verifies if the object has been already created and in this case it just returns created and if not it creates new one and returns it. See:

public class UnitsFactory {
   
    private static Map<Class, Unit> _units = new WeakHashMap<Class, Unit>();
       
    public static Dog createDog(){
    Class dogClass = Dog.class;
   
    if(! _units.containsKey(dogClass))
        _units.put(dogClass, new Dog());
   
    return (Dog) _units.get(dogClass);
    }
   
    public static Dragon createDragon(){
    Class dragonClass = Dragon.class;
   
    if(! _units.containsKey(dragonClass))
        _units.put(dragonClass, new Dragon());
   
    return (Dragon) _units.get(dragonClass);   
    }
}

Lets take a look on UML diagram of our code:

UnitsFactory corresponds to FlyweightFactory, Unit – for Flyweight. Dog, Dragon corresponds to concrete Flyweights in the GoF FlyWeithgt naming.

Now we will do change to our parser to use Factory and will see how much of memory will it take.
But now we are going to create 1500 Dragons and 60000 Dogs, probably your gamer is quite more quick as you think.

    for(int i = 0; i < 1500; ++i)
        result.add(UnitsFactory.createDragon());
   
    for(int i = 0; i < 60000; ++i)
        result.add(UnitsFactory.createDog());
 

       
And this takes only about 5 Mb of memory:

What have I learned regarding to of Java?
I know that corresponding to C# Dictionary is Map in Java, and there are few concrete maps like on this good picture:

Hope this was a good story!

Go to: My Design Patterns Table