🧬Prototype Pattern – Overview
🧠 Concept
🧱 Key Roles
Role
Description
💻 Java Example – UI Button Prototype
// ----- Prototype Interface -----
interface UIComponent extends Cloneable {
UIComponent clone();
void render();
}
// ----- Concrete Prototype -----
class Button implements UIComponent {
private String color;
private String label;
public Button(String color, String label) {
this.color = color;
this.label = label;
}
// Clone method
public UIComponent clone() {
return new Button(this.color, this.label);
}
public void render() {
System.out.println("Button: " + label + " [" + color + "]");
}
}
// ----- Another Concrete Prototype -----
class Checkbox implements UIComponent {
private boolean checked;
public Checkbox(boolean checked) {
this.checked = checked;
}
public UIComponent clone() {
return new Checkbox(this.checked);
}
public void render() {
System.out.println("Checkbox: " + (checked ? "Checked" : "Unchecked"));
}
}
// ----- Client -----
class PrototypeRegistry {
private Map<String, UIComponent> prototypes = new HashMap<>();
public void register(String key, UIComponent prototype) {
prototypes.put(key, prototype);
}
public UIComponent create(String key) {
UIComponent prototype = prototypes.get(key);
return prototype != null ? prototype.clone() : null;
}
}🧠 Flow Summary
Step
Action
Result
🪜 Summary
🧾 Real-world Analogy
🧭 TL;DR
Last updated