Prototype Pattern: Interview Deep Dive
Interviewers test whether you understand cloning mechanics, handle edge cases, and make appropriate design decisions. They often ask about deep vs shallow copying, performance implications, and alternatives.
"When would you use shallow copy vs deep copy in Prototype pattern?"
Document has a metadata object containing author and creation date (immutable), shallow copy is fine. But if it has a paragraphs list that can be edited, deep copy prevents changes in one document affecting another. Always ask the interviewer about mutability assumptions upfront."How do you handle circular references when cloning?"
if obj in cache:
return cache[obj]
clone = new obj.constructor()
cache[obj] = clone
for each field in obj:
clone[field] = deepClone(obj[field], cache)
return clone
"Design a prototype registry for a parking lot with different vehicle types."
VehicleRegistry that stores prototype instances mapped to vehicle types. When creating a vehicle, look up the prototype and clone it. This avoids rebuilding complex vehicle configurations each time.prototypes: Map<String, Vehicle>
function register(type: String, prototype: Vehicle):
prototypes[type] = prototype
function createVehicle(type: String): Vehicle
if type not in prototypes:
throw InvalidVehicleType
return prototypes[type].clone()
// Usage
registry.register("MOTORCYCLE", new Motorcycle(wheels=2))
registry.register("CAR", new Car(wheels=4, doors=4))
bike = registry.createVehicle("MOTORCYCLE")
In a timed coding round, focus on correctness first. Start with shallow copy, then add deep copy only for fields that need it. Document assumptions about immutability. If the problem involves complex nested structures, discuss with the interviewer whether full deep cloning is required or if selective field-by-field copying is acceptable. Always handle null checks when cloning references.
List<Item> items, ensure you create a new list and clone each item if items are mutable. Simply copying the reference creates shared state bugs.First, Copy Constructor: Instead of a clone() method, use a constructor that takes an existing instance. This is clearer in languages without native clone support. Second, Serialization-based Cloning: Serialize the object to bytes and deserialize to create a copy. This handles deep cloning automatically but is slower. Third, Clone Builder: Combine with Builder pattern to allow customization after cloning (clone then modify specific fields).