Design Patterns

Notes and exercises for learning design patterns

View the Project on GitHub Claptar/design-patterns

Exercise 2: Deep Copying Nested State

Goal

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.


Story

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.


Your task

Open exercise2.py and implement:

def clone(self, **changes) -> "Dashboard":
    ...

This time the clone must be independent from the original, including:


Tests to satisfy

The tests check that:

Run:

python exercise2.py

Hint

Use copy.deepcopy().

The point of this exercise is to feel the difference between:

copy.copy(obj)

and:

copy.deepcopy(obj)