SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 14 / 42

Junior

What is the Prototype pattern? How do shallow and deep copies differ?

Short answer

Prototype creates a new object by copying an existing template object instead of building from scratch, worth it when building is expensive and copies differ in a few fields. You must say whether it's a shallow or deep copy.

shallow copydeep copysharesTemplateShallow cloneDeep cloneOriginal items listNew items list

3 points to say:

  1. Prototype: create objects by copying a template, when building from scratch is expensive (reading config, parsing templates).
  2. Shallow copy shares child objects, so changing one leaks into the other; deep copy copies the children too.
  3. Use a copy constructor / copy factory, avoid clone(); prefer immutable objects.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.