This is its definition:
Use sharing to support large numbers of fine-grained objects efficiently.
But I can't figure out what it means exactly.
Can you elaborate with a tiny demo?
Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.
In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns.
The Flyweight pattern is useful if you need a large number of instances of a particular type. You isolate the data that is the same for all these instances (the intrinsic state) into a shared object. You only keep the data that varies per instance in the instances themselves (the extrinsic state). The benefit is less memory consumption obviously.
It's a common pattern in the gaming industry where the usual example is Soldiers on the battle field. All Soldiers share the same graphical representation and the same weapons but their position and health is different. The extrinsic state would then only be their health and x/y/z coordinates on the battlefield while everything else would be in the Flyweight.
PHP Implementations for this pattern are easy to find on the web. For instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With