Junior — Middle
Explain the differences between Singleton and Prototype patterns in terms of scope and object usage.
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that only one instance of a class exists in the application, which is accessible globally. The scope of the object is global, and all clients work with the same object. This is convenient for managing shared resources, such as configuration or connection pools.
The Prototype pattern involves creating new objects by cloning an existing prototype. Each call creates a new independent instance. The scope is local to each created object, allowing multiple similar but independent objects.
Example in Java:
// Singleton
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
// Prototype
public class Prototype implements Cloneable {
private int value;
public Prototype(int value) { this.value = value; }
public Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
Thus, Singleton is one object for the entire application, Prototype is a set of objects created based on a template.