The Flyweight Structural Pattern in Java

Intent: Considered as a structural pattern, the flyweight pattern helps in sharing the objects efficiently.

Motivation: In situations where you need to create several objects and many of the them may represent the same value. In these instances, it is possible to share the values as long as the objects are immutable.

Implementation: A good example of implementing the flyweight pattern could be extracted from the Integer class from the Java standard library.

 * Returns an {@code Integer} instance representing the specified
 * {@code int} value. If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 * @param i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since 1.5
 public static Integer valueOf(int i) {
     if (i >= IntegerCache.low && i <= IntegerCache.high)
     return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);

Now let’s test our pattern:

 public void sameIntegerInstancesTest(){
     final Integer a = Integer.valueOf(36);
     final Integer b = Integer.valueOf(36);
     assertSame(a, b);
     final Integer c = Integer.valueOf(524);
     final Integer d = Integer.valueOf(524);
     assertNotSame(c, d);


a and b represent the same object because they are available in the values that are cached, whereas c and d are out of the range of the cached values, an object is created for each.

Leave Comment

Your email address will not be published. Required fields are marked *