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.
3 points to say:
- Prototype: create objects by copying a template, when building from scratch is expensive (reading config, parsing templates).
- Shallow copy shares child objects, so changing one leaks into the other; deep copy copies the children too.
- 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.