To conclude this chapter on structural design patterns, we'll dive into the flyweight pattern. You may want to use the flyweight pattern when:
- You create many instances of the same object
- You can afford to use memory to cache instances
- You do not mutate those instances, and can afford to share them across your program
Let's say you want to build an application to help with groceries and recipes. As input, we may have lists of ingredients and their amounts, based on their names, as strings. We want to be able to make lists, organize them, and more.
While we technically could store the strings as our base items, we'll use the flyweight pattern to encapsulate those item names. This will help us be more accurate in the rest of our program. Instead of using strings around, we'll use proper instances.