Notes and exercises for learning design patterns
Practice the smallest useful version of the Prototype pattern.
In this first part, a dashboard can clone itself and accept small changes.
You should be able to write:
uk_dashboard = template.clone(
title="UK Sales Dashboard",
owner="Alice",
)
The cloned dashboard should be a new object. The original dashboard should keep its original top-level values.
Your analytics team has a standard dashboard template.
The template already has:
title
owner
layout
widgets
filters
refresh interval
For now, focus only on the basic idea:
Take this existing dashboard.
Make a copy.
Change a few fields on the copy.
Return the copy.
Open exercise1.py and implement:
def clone(self, **changes) -> "Dashboard":
...
The method should:
setattr,For this first exercise, the tests only check top-level fields.
The tests check that:
clone() returns a different Dashboard object,Run:
python exercise1.py
You may use copy.copy() or copy.deepcopy() here.
In the next exercise, you will see why shallow copying is not always enough.