Notes and exercises for learning design patterns
Improve the dashboard prototype so cloned dashboards do not accidentally share nested mutable objects.
This is the most important practical detail in the Prototype pattern.
The first clone worked for top-level fields.
But dashboards contain nested mutable state:
widgets -> list of Widget objects
filters -> dictionary of filter values
If two dashboards share the same filters dictionary or the same Widget objects, changing one dashboard can accidentally change the other.
That is not a safe clone.
Open exercise2.py and implement:
def clone(self, **changes) -> "Dashboard":
...
This time the clone must be independent from the original, including:
widgets list,Widget inside the list,filters dictionary.The tests check that:
Dashboard,Run:
python exercise2.py
Use copy.deepcopy().
The point of this exercise is to feel the difference between:
copy.copy(obj)
and:
copy.deepcopy(obj)