Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:
See bookFlyweight
Structural patternFlyweight is a pattern dedicated to building light objects by abstracting parts that can be reused and shared in order to create new objects when required, and reusing objects created by other instances, significantly reducing the amount of memory being used by the application.
This pattern is useful when resource optimization is fundamental, because it eliminates redundancy on objects with identical properties.
The components included in the pattern are:
- Client: Object which triggers the execution.
- FlyweightFactory: Factory for building the Flyweight objects.
- Flyweight: It refers to the objects we want to reuse in order to create lighter objects.
- The client requests the Factory for the creation of a Flyweightobject.
- Before creating the object, the Factory checks if there's an identical object to the one being requested, if so, it returns the existing object; if not, it will create the new object and store it in a cache for further use.
- The Flyweight object is created or borrowed from the cache and returned to the client.
Real-world example
By implementing the Flyweight design pattern, we are going create an application for managing playlists. Some songs must be shared between various playlists, and some songs must have shared sections between them in order to save memory space.