Flyweight is a structural design pattern that allows programs to support vast quantities of objects by keeping their memory consumption low.
The pattern achieves it by sharing parts of object state between multiple objects. In other words, the Flyweight saves RAM by caching the same data used by different objects.
Usage examples: The Flyweight pattern is especially rarely used in PHP applications due to the very nature of the language. A PHP script typically works with a part of the application’s data and never loads all of it into the memory at the same time.
Identification: Flyweight can be recognized by a creation method that returns cached objects instead of creating new.
Conceptual Example
This example illustrates the structure of the Flyweight design pattern and focuses on the following questions:
What classes does it consist of?
What roles do these classes play?
In what way the elements of the pattern are related?
After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real-world PHP use case.
index.php: Conceptual example
Output.txt: Execution result
Real World Example
Before we begin, please note that real applications for the Flyweight pattern in PHP are pretty scarce. This stems from the single-thread nature of PHP, where you’re not supposed to be storing ALL of your application’s objects in memory at the same time, in the same thread. While the idea for this example is only half-serious, and the whole RAM problem might be solved by structuring the app differently, it still demonstrates the concept of the pattern as it works in the real world. All right, I’ve given you the disclaimer. Now, let’s begin.
In this example, the Flyweight pattern is used to minimize the RAM usage of objects in an animal database of a cat-only veterinary clinic. Each record in the database is represented by a Cat object. Its data consists of two parts:
Unique (extrinsic) data such as a pet’s name, age, and owner info.
Shared (intrinsic) data such as breed name, color, texture, etc.
The first part is stored directly inside the Cat class, which acts as a context. The second part, however, is stored separately and can be shared by multiple cats. This shareable data resides inside the CatVariation class. All cats that have similar features are linked to the same CatVariation class, instead of storing the duplicate data in each of their objects.