Prototype Pattern
Bryan Hansen
twitter: bh5k | http://www.linkedin.com/in/hansenbryan
Concepts
▪ Avoids costly creation
▪ Avoids subclassing
▪ Typically doesn’t use “new”
Drag picture to
▪ Often utilizes an Interface placeholder or click
icon to add a graphic
▪ Usually implemented with a Registry
▪ Example:
▪ java.lang.Object#clone()
Design
Clone / Cloneable
Avoids keyword “new”
Although a copy, each instance unique
Costly construction not handled by client
Can still utilize parameters for construction
Shallow VS Deep Copy
Everyday Example - Object Clone
public class Statement implements Cloneable {
public Statement(String sql, List<String> parameters, Record record) {
this.sql = sql;
this.parameters = parameters;
this.record = record;
}
public Statement clone() {
try {
return (Statement) super.clone();
} catch (CloneNotSupportedException e) {}
return null;
}
}
Exercise Prototype
Create Prototype
Demonstrate shallow copy
Create with a Registry
Pitfalls
▪ Sometimes not clear when to use
▪ Used with other patterns
▪ Registry
▪ Shallow VS Deep Copy
Contrast
Prototype Factory
▪ Lighter weight construction ▪ Flexible Objects
▪ Copy Constructor or Clone ▪ Multiple constructors
▪ Shallow or Deep ▪ Concrete Instance
▪ Copy of itself ▪ Fresh Instance
Prototype Summary
• Guarantee unique instance
• Often refactored in
• Can help with performance issues
• Don’t always jump to a Factory