Junior
What is the difference between singleton and prototype patterns?
sobes.tech AI
Answer from AI
-
Singleton: Ensures that a class has only one instance and provides a global point of access to it. Used when a single object is needed to coordinate actions across the system (e.g., logging, caching).
public class Singleton { private static Singleton instance; private Singleton() {} // Private constructor public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } // ... other methods } -
Prototype: Specifies the types of objects to create using a prototypical instance and creates new objects by copying this prototype. Used when object creation is expensive or complex, or when many similar objects with small differences are needed.
public class Prototype implements Cloneable { private String property; public Prototype(String property) { this.property = property; } public void setProperty(String property) { this.property = property; } public String getProperty() { return property; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); // Default shallow copy } // ... other methods }
Main differences:
| Characteristic | Singleton | Prototype |
|---|---|---|
| Purpose | Single instance of a class | Creating copies of existing objects |
| Number of objects | Always one instance | Arbitrary number of copies |
| Access method | Via static method getInstance() |
Via clone() method (copying the prototype) |
| Copying | Not applicable | Used (shallow or deep copy) |