Flyweight pattern
Key 7: Consuming less memory with shared objects.
A flyweight design pattern is useful to save memory. When we have lots of object count, we store references to previous similar objects and provide them instead of creating new objects. In the following example, we have a Link
class used by the browser, which stores the link data.
The browser uses this data, and there may be a lot of data that is associated with pictures referenced by the link, such as image content, size, and so on, and images can be reused over the page. Hence, the nodes using it only store a flyweight BrowserImage
object to decrease the memory footprint. When the link class tries to create a new BrowserImage
instance, the BrowserImage
class checks whether it has an instance in its _resources
mapping for the resource path. If it does, it will just pass the old instance:
import weakref class Link(object): def __init__(self, ref, text, image_path=None): self.ref = ref if image_path...