A Flyweight Example In Python

Learn to utilize Flyweight design pattern to maintain code efficiency using an example.

Overview

We’ll start with some concrete classes for an IoT device that works with GPS messages. We don’t want to create a lot of individual Message objects with duplicate values taken from a source buffer; instead, we want Flyweight objects to help save memory. This leverages two important features:

  • The Flyweight objects reuse bytes in a single buffer. This avoids data duplication in a small computer.

  • The Flyweight classes can have unique processing for the various message types. In particular, the GPGGA, GPGLL, and GPRMC messages all have latitude and longitude information. Even though the details vary by message, we don’t want to create distinct Python objects. It’s a fair amount of overhead to handle the case when the only real processing distinction is the location of the relevant bytes within a buffer.

Here’s the UML diagram:

Get hands-on with 1400+ tech skills courses.