Implementation

Since I already mentioned the tree example, let's see how we can implement it. In this example, we will create a very small forest of fruit trees. It is small to make sure that the whole output is readable in a single terminal page. However, no matter how large you make the forest, the memory allocation stays the same. An Enum parameter describes the three different types of fruit trees as follows:

TreeType = Enum('TreeType', 'apple_tree cherry_tree peach_tree')

Before diving into the code, let's spend a moment to note the difference between memoization and the Flyweight pattern. Memoization is an optimization technique that uses a cache to avoid recomputing results that were already computed in an earlier execution step. Memoization ...

Get Mastering Python Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.