Motivation: Some classes must have exactly one instance (e.g., a file system, a database connection pool, a window manager).
Intent: Ensure a class has only one instance and provide a global point of access to it.
Here, we enforce a single source of truth.
object DatabaseConnection {
fun query(sql: String): List<String> {
// ...
return listOf()
}
}
// Usage---only one instance ever exists
val result = DatabaseConnection.query("SELECT * FROM users")Then we pass around this single connection.
class Singleton {
// keep the constructor private to prevent other classes from instantiating it
private Singleton() { /* ... */ }
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) { instance = new Singleton(); }
return instance;
}
}