The singleton pattern is a creational pattern that allows you to make sure that only one instance of a class is created.
Use the Singleton pattern when:
You can find the full example source code here.
In the example I'm going to apply the Singleton pattern to a class that represents a database connection.
class Database {
private static instance: Database;
}
For the example, the constructor won't have any parameters. In a real-world scenario, you might want to pass some configuration to the constructor.
class Database {
private static instance: Database;
private constructor() {}
}
class Database {
private static instance: Database;
private constructor() {}
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
class Database {
private static instance: Database;
private constructor() {}
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
public query(sql: string): void {
console.log(`Querying database: ${sql}`);
}
}
An example of how client code would use the Singleton instance:
const database = Database.getInstance();
database.query("SELECT * FROM users");
// Output:
// Querying database: SELECT * FROM users
const database2 = Database.getInstance();
if (database === database2) {
console.log(
"The same instance of Database was returned. The Singleton pattern works!"
);
} else {
console.log(
"A new instance of Database was returned. The Singleton pattern failed."
);
}
// Output:
// The same instance of Database was returned. The Singleton pattern works!