Junior — Middle
Can you give an example of a situation where you applied the Prototype pattern in your practice?
sobes.tech AI
Answer from AI
In one of my Java projects, I needed to create many objects with the same structure but slight data differences. Instead of creating each object from scratch, I applied the Prototype pattern — implemented the Cloneable interface and overridden the clone() method. This allowed me to quickly create copies of the original object, saving time and resources.
Example:
class Document implements Cloneable {
private String content;
public Document(String content) {
this.content = content;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// Usage
Document original = new Document("Original text");
Document copy = (Document) original.clone();
copy.setContent("Modified text");
This approach helped avoid recreating complex objects and simplified state management.