Creational Patterns • Prototype PatternMedium⏱️ ~2 min
Prototype Pattern Structure
Core Participants:
The pattern consists of the Prototype interface that declares the cloning method, ConcretePrototype classes that implement cloning logic, and a Client that requests clones without knowing concrete types.
«interface»
Prototype
+ clone(): Prototype
▲
ConcretePrototypeA
- fieldX: Type
- fieldY: Type
- fieldY: Type
+ clone(): Prototype
ConcretePrototypeB
- fieldZ: Type
- nestedObj: Object
- nestedObj: Object
+ clone(): Prototype
Client
- prototype: Prototype
+ createCopy(): Prototype
Relationships:
The inheritance relationship (▲) shows that concrete prototypes implement the Prototype interface. The client holds a reference to the Prototype interface and calls clone() without knowing the concrete type.
Clone Method Implementation:
Each ConcretePrototype implements clone() to return a copy of itself. For shallow copying, simply copy primitive fields and references. For deep copying, recursively clone nested objects. The choice depends on whether clones should share mutable state.
function clone():
newObj = new ConcretePrototypeA()
newObj.fieldX = this.fieldX
newObj.fieldY = this.fieldY
return newObj
newObj = new ConcretePrototypeA()
newObj.fieldX = this.fieldX
newObj.fieldY = this.fieldY
return newObj
Interview Tip: Clarify whether the interviewer expects deep or shallow cloning. Ask about mutable nested objects upfront. This shows you understand the subtleties of object copying.
💡 Key Takeaways
✓Prototype interface defines the clone contract
✓Each concrete prototype implements its own cloning logic
✓Client works with the Prototype interface, not concrete classes
✓Cloning can be shallow (copy references) or deep (copy nested objects)
✓The pattern decouples object creation from the client code
📌 Examples
1Shape hierarchy where each shape knows how to clone itself
2Configuration objects that need variations without rebuilding from scratch