Middle+
Where and when have you used the Prototype pattern?
sobes.tech AI
Answer from AI
The Prototype pattern is used when there is a need to create many similar objects with minimal costs. For example, when working with a user interface to create identical visual elements or when generating data for tests.
A specific example: creating a series of Image objects for display in a gallery. Instead of loading and processing each image separately, a single "prototype" Image object with common properties (such as size, effects) is created, and then its instances are cloned, with only the file path changed for each.
// Prototype implementation example
public class Image implements Cloneable {
private String filePath;
private int width;
private int height;
public Image(String filePath, int width, int height) {
this.filePath = filePath;
this.width = width;
this.height = height;
}
// Getters and setters
@Override
protected Object clone() throws CloneNotSupportedException {
// Shallow copy
return super.clone();
}
// Method to display the image
public void display() {
System.out.println("Displaying image: " + filePath + " (" + width + "x" + height + ")");
}
}
public class ImageGallery {
private Image prototypeImage;
public ImageGallery(int width, int height) {
// Create a prototype with common properties
this.prototypeImage = new Image(null, width, height);
}
public Image createImage(String filePath) {
try {
// Clone the prototype
Image newImage = (Image) prototypeImage.clone();
// Set specific property
newImage.setFilePath(filePath);
return newImage;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
ImageGallery gallery = new ImageGallery(800, 600);
// Create images based on the prototype
Image img1 = gallery.createImage("path/to/image1.jpg");
Image img2 = gallery.createImage("path/to/image2.png");
Image img3 = gallery.createImage("path/to/image3.gif");
img1.display();
img2.display();
img3.display();
}
}