Dezign Patterns
Prototype Design Pattern
The Prototype Pattern is used to create new objects by copying an existing object, which is referred to as a prototype.
Let's take an example of template , which is used across the Organization.
Everytime we create a report , we use the template and fill the data.
- Template Reuse: Styles and formats are reused without recreating them every time.
- Performance: No need to reapply formatting logic on each report.
- Consistency: Ensures reports follow an organization-wide standard.
Example
I - Prototype Interface
public abstract class ExcelReport implements Cloneable {
protected String headerStyle;
protected String cellStyle;
protected String footer;
public abstract void fillData(String[][] data);
public abstract void export(String filename);
@Override
public ExcelReport clone() {
try {
return (ExcelReport) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Cloning not supported", e);
}
}
}
II - Concrete Template
public class StandardExcelReport extends ExcelReport {
private String[][] data;
public StandardExcelReport() {
this.headerStyle = "Bold | Blue Background";
this.cellStyle = "Bordered | Font: Calibri 11";
this.footer = "Confidential © 2025";
this.data = new String[0][];
}
@Override
public void fillData(String[][] data) {
this.data = data;
}
@Override
public void export(String filename) {
System.out.println("Exporting Report: " + filename);
System.out.println("Header Style: " + headerStyle);
System.out.println("Cell Style: " + cellStyle);
System.out.println("Footer: " + footer);
System.out.println("Data:");
for (String[] row : data) {
for (String cell : row) {
System.out.print(cell + " | ");
}
System.out.println();
}
System.out.println("File saved as " + filename + "
");
}
}
III - Prototype Cache
import java.util.HashMap;
import java.util.Map;
public class ReportManager {
private Map<String, ExcelReport> templates = new HashMap<>();
public void addTemplate(String key, ExcelReport report) {
templates.put(key, report);
}
public ExcelReport getClonedReport(String key) {
ExcelReport template = templates.get(key);
return template != null ? template.clone() : null;
}
}
IV - Client Code
public class ExcelPrototypeDemo {
public static void main(String[] args) {
// Initialize template
ReportManager manager = new ReportManager();
ExcelReport standardTemplate = new StandardExcelReport();
manager.addTemplate("standard", standardTemplate);
// Clone and use for Report 1
ExcelReport report1 = manager.getClonedReport("standard");
report1.fillData(new String[][] {
{"Name", "Sales", "Region"},
{"Alice", "5000", "East"},
{"Bob", "7000", "West"}
});
report1.export("SalesReport_Q1.xlsx");
// Clone and use for Report 2
ExcelReport report2 = manager.getClonedReport("standard");
report2.fillData(new String[][] {
{"Name", "Hours", "Project"},
{"John", "40", "Alpha"},
{"Doe", "35", "Beta"}
});
report2.export("Timesheet_May.xlsx");
}
}