The Flyweight Pattern

The flyweight pattern seeks to avoid redundancy when storing data. It is a space optimization technique that uses less memory by storing data from similar objects.

Let’s say we want to render the movements of an animal on map based on GPS coordinates collected every 10 seconds from an implanted GPS device. The data collected are represented by a list of GpsPoint:

public class GpsPoint {
  private double longitude;
  private double latitude;
  private double altitude;

  // getters/setters
}

Now we may want to track multiple animals on a single map. The number of points can quickly increase. We can use a buffer to keep in memory duplicated points. Indeed, the animal may stay or go back to the same spots. Our buffer can be very simple:

public class Buffer<GpsPoint> {

   private List<GpsPoint> points;

   public boolean contains(GpsPoint point) {
      return points.contains(point); // assume GpsPoint overrode equals() and hashcode()
   }

   // ...
}

We would need a buffer manager or the renderer can manage the buffer. For example, it would check if the point exists in the buffer before adding it:

public class Renderer {

   private Buffer<GpsPoint> buffer;

   public void render(GpsPoint point) {
       if (!buffer.contains(point)) { // does not keep duplicate in memory
          buffer.add(point);
       }

       buffer.forEach(pt -> drawPoint(pt)); // render each point of the buffer
   }

}

Buffer has less points than what the trace has. Simple technique… the most complicated part of this pattern is probably its name 🙂

Leave a comment

Design a site like this with WordPress.com
Get started