Flyweight Design Pattern

So you have a group of objects that can be reused, but each time you use one you have to create it first. The problem is that instantiating these types of objects is expensive, and you don't want to instantiate the same kind every time you need it. Enter Flyweight design pattern. With this pattern, the trick is to create a new object only when you've never created that same type of object before - if you HAVE created it before, then simply look it up and use the one that's already instantiated. Here's some code:

public class Flyweight
{
    public static Dictionary _Table = new Dictionary();

    public ISomething GetSomething(int key)
    {
        ISomething something;
        if(_Table.TryGetValue(key, ref something))
        {
            return something;
        }
        else
        {
            something = new Something(key);
            _Table.Add(key, something);
            return something;
        }
    }
}

What this code does is ensure that the only time an object of type ISomething is instantiated is when there's a type requested that hasn't been requested before. Otherwise it'll return the one that was requested before. The GOOD: saves clock cycles by instantiating each type only once. The potentially BAD: uses more memory than creating new instances on the fly. Cheers.

Comments

Popular Posts