Click here to Skip to main content
Licence CPOL
First Posted 8 Feb 2010
Views 4,801
Bookmarked 3 times

FlyWeight

By Andriy Buday | 8 Feb 2010 | Technical Blog
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. Memory issue? - FLYWEIGHT will
A Technical Blog article. View original blog here.[^]

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andriy Buday

Software Developer
SoftServe
Ukraine Ukraine

Member
I'm very pragmatic and self-improving person. My goal is to become successful community developer.
I'm young and love learning, these are precondition to my success.
 
Currently I'm working in dedicated Ukrainian outsourcing company SoftServe as .NET developer on enterprise project. In everyday work I'm interacting with lot of technologies which are close to .NET (NHibernate, UnitTesting, StructureMap, WCF, Win/WebServices, and so on...)
 
Feel free to contact me.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionSo all the units have the same health? Pinmemberfredito4:06 17 Feb '10  
AnswerRe: So all the units have the same health? PinmemberAndriy Buday22:51 17 Feb '10  
I'm sorry, my example is not so clear.
 
The main purpose of Flyweight is to utilize/share same instances of massive objects, this could be needed when you need to have a lot of similar objects that share same resource like image for Dragon in memory.
 
So you are correct that current design is bad especially for game.
 
Better is to have UnitImagesFactory, which is flyweight factory, and it can return Images of Dragon or either Dog, so only one allocation of memory for each image.
This factory should/will be used in constructor of particular Unit.
 
This way all properties will be different instances and each Unit will have it's health. Only image of Dragon will be the same instance for all Dragons.
 
fredito, is my design better now?
GeneralRe: So all the units have the same health? Pinmemberfredito4:15 18 Feb '10  
Questioncan you explain...? PinmemberHerre Kuijpers22:22 8 Feb '10  
AnswerRe: can you explain...? PinmemberAndriy Buday0:36 9 Feb '10  
GeneralRe: can you explain...? PinmemberHerre Kuijpers22:21 10 Feb '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120210.1 | Last Updated 8 Feb 2010
Article Copyright 2010 by Andriy Buday
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid