Junior — Middle
How do the Singleton and Prototype patterns differ in the context of object-oriented programming?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it. This is useful when you need to control access to a resource, such as configuration or a logger.
Example of Singleton in Java:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The Prototype pattern is used to create new objects by cloning an existing instance. This is convenient when creating an object from scratch is costly or complex, and copying an already configured object is easier.
Example of Prototype in Java:
public class Prototype implements Cloneable {
private int field;
public Prototype(int field) {
this.field = field;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Main difference:
- Singleton restricts the number of instances to one.
- Prototype allows creating new objects by copying existing ones.