Master the Prototype Pattern in Java: Clone Objects Efficiently
This article explains the Prototype design pattern, illustrating how to clone complex Java objects efficiently by sharing resources, with clear analogies, diagrams, and complete code examples that demonstrate creating, caching, and retrieving prototype instances.
1. Initial Prototype Pattern
Copying homework is used as a metaphor for quickly reusing existing solutions, and the Prototype design pattern is introduced to model this concept in Java. Unlike the Flyweight pattern, which shares a single instance, the Prototype pattern creates copies of an existing object.
The Prototype pattern (Prototype Pattern) creates duplicate objects while preserving performance and belongs to the creational design patterns. It is useful when object creation is resource‑intensive or time‑consuming.
2. Diagram of Prototype Pattern
The diagram shows two prototype objects: XiaoQi (kind, gentle, versatile) and XiaoZi (generous, intellectual, filial). To avoid the time cost of finding such objects repeatedly, one can request an object "like XiaoQi" and obtain a copy.
When cloning, only height, weight, and hobbies (a reference type) are copied; the name is intentionally not duplicated.
3. Code Implementation
Base class Girl defines the fields and a cloneGirl method.
package prototype;
import java.util.List;
public class Girl {
// name
String name;
// height cm
int height;
// weight kg
int weight;
// hobbies
List<String> natures;
// clone method
public Girl cloneGirl(){
// no initialization, returns null if not overridden
return null;
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
", height=" + height +
", weight=" + weight +
", natures=" + natures +
'}';
}
}Concrete prototype GirlLikeXiaoQi initializes XiaoQi’s attributes.
package prototype;
import java.util.ArrayList;
import java.util.Arrays;
public class GirlLikeXiaoQi extends Girl{
public GirlLikeXiaoQi(){
this.name = "小琪";
this.height = 165;
this.weight = 60;
this.natures = Arrays.asList("善良","温柔","多才多艺");
}
@Override
public Girl cloneGirl() {
Girl girl = new Girl();
// name not copied
girl.height = this.height;
girl.weight = this.weight;
// deep copy of hobbies
girl.natures = new ArrayList<>(this.natures);
return girl;
}
}Concrete prototype GirlLikeXiaoZi initializes XiaoZi’s attributes.
package prototype;
import java.util.ArrayList;
import java.util.Arrays;
public class GirlLikeXiaoZi extends Girl{
public GirlLikeXiaoZi(){
this.name = "小紫";
this.height = 175;
this.weight = 70;
this.natures = Arrays.asList("大方","知性","孝顺");
}
@Override
public Girl cloneGirl() {
Girl girl = new Girl();
// name not copied
girl.height = this.height;
girl.weight = this.weight;
girl.natures = new ArrayList<>(this.natures);
return girl;
}
}Cache class stores prototype instances.
package prototype;
import java.util.HashMap;
public class GirlCache {
static HashMap<String, Girl> girls;
static {
girls = new HashMap<>();
girls.put("小琪", new GirlLikeXiaoQi());
girls.put("小紫", new GirlLikeXiaoZi());
}
static Girl getGirl(String name){
if(girls.containsKey(name)){
return girls.get(name).cloneGirl();
} else {
return null;
}
}
}Test class demonstrates usage.
package prototype;
public class Test {
public static void main(String[] args) {
// original XiaoQi
Girl xiaoqi = GirlCache.girls.get("小琪");
System.out.println(xiaoqi);
// clone of XiaoQi
Girl likeXiaoQi = GirlCache.getGirl("小琪");
System.out.println(likeXiaoQi);
// modify clone without affecting original
likeXiaoQi.name = "小琪表妹";
likeXiaoQi.natures.add("幽默");
System.out.println(likeXiaoQi);
System.out.println(xiaoqi);
// request non‑existent prototype
Girl likeyaya = GirlCache.girls.get("伢伢");
System.out.println("小亮对象:"+likeyaya);
// clone XiaoZi and modify
Girl likexiaozi = GirlCache.getGirl("小紫");
likexiaozi.name = "紫棋";
likexiaozi.natures.add("超喜欢唱歌");
System.out.println("小明对象:"+likexiaozi);
}
}4. Test Output
The program prints the original objects, their clones, and demonstrates that changes to a clone do not affect the cached prototype.
5. Conclusion
The Prototype pattern provides a convenient way to obtain objects that share the same state except for selected fields, much like copying homework; it enables efficient object creation without the overhead of building each instance from scratch.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
