The singleton pattern is one of five design patterns in the Creational Design Pattern group. The singleton ensures only a single install is created in a class and provides a method to access this instance everywhere in a codebase.
The singleton pattern should be used when a developer wants to:
For example, We will define a class that has a responsibility to get a database connection only.
export class DatabaseConnection { private static isConnected: boolean = false; private static db: Promise<DataSource>; public static getConnection(): Promise<DataSource> { if (this.isConnected) { return Promise.resolve(this.db); } this.db = this.connect(); return Promise.resolve(this.db); } private static connect(): Promise<DataSource> { try { const con = new DataSource({}); return con .initialize() .then(() => { this.isConnected = true; console.log('DB connection is OK'); return Promise.resolve(con); }) .catch((error) => { console.log('DB connection is BAD'); return Promise.reject(error); }); } catch (error) { return Promise.reject(error); } } }
MySQLConnection.getConnection() .then(() => { server = app.listen(config.port, () => { logger.info(`Listening to port ${config.port as number}`); }); }) .catch(() => logger.error('Server error!'));
Pros:
Cons:
Thank you for reading, and happy coding!
I hope this article will help make the concepts of the Singleton Pattern