Describe an implementation of the Flyweight Pattern?

The Flyweight Pattern can be a useful pattern in situations where we have several objects, and many of those are representing the same value. In these instances, it can be possible to share the values as long as the objects are immutable. The following example shows from the Java standard library, taken from Sun’s implementation of the Integer class.

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high) 
         return IntegerCache.cache[ i + ( -IntegerCache.low)];
    return new Integer(i);

The valueOf method checks the value of the given parameter, and if it is a preached value, the method returns the constructed instance rather than creating a new copy. The default range of the cache is -128 to 127. This Integer cache is initialized in a static block, and is created for the first time when an Integer is referenced in a running JVM: 

static { 
    // setup of the cache size omitted    
    for (int k = 0; k < cache.length; k++) 
       cache[k] = new Integer(j++);

Following Test case proves that the Integer cache uses Flyweight Pattern, because the Integer a and b are same instances, not only equals in Content.

public void sameIntegerInstances() {
    final Integer a = Integer.valueOf(56);
    final Integer b = Integer.valueOf(56);
    assertSame(a, b);
    final Integer c = Integer.valueOf(472);
    final Integer d = Integer.valueOf(472);
    assertNotSame(c, d);

This property only holds because Integer objects are immutable. If you could change the value of the Integer object after it was constructed, then when it was used with the Flyweight Pattern, changing one value would have a knock-on effect to every other reference to that object. If you are ever creating Integer objects, always use the valueOf method to take advantage of the Flyweight Pattern. If you call new, then new instances will always be  created, even if they are within the threshold of the cached values. A Flyweight Pattern is applicable in many situations; another implementation of the Flyweight Pattern is called the Null Object Pattern. This pattern uses a flyweight object to represent null. When creating data structures such as a binary tree, the tree leaves will have no children. Depending on your implementation, it may be sufficient to simply use null references, or you may want to use a null object. This would be imagined as each leaf having its own null object, but in practice, you may be able to use a single flyweight object.