Use sharing to support large numbers of fine-grained objects efficiently
Let's put the definition above into practice. We have a list of three library that will be used differently at run time, the libraries' state can be made extrinsically such as name and ID. There is no need to re-create these fields all over again to save memory footprint. We would need a factory and cache pool to alleviate that. First up, we want to have a library structure as below
Then, we want to define a function that create different initial library state like below
Last but not least, we need to implement a Library factory that contain the cache that store already created library and couple of utility methods to verify the success of application.
And there we have a complete implementation of Flyweight Pattern in Go. With this library, memory can be saved a ton at scale in tradeoff a more complexity added to the codebase. Hence, this pattern should be used with caution
P/s: The accompany code is included in this PR 😊
Happy coding 😎