Singleton Pattern in JavaScript

preview_player
Показать описание
This video is an introduction to singleton pattern in JavaScript

Social Media Links:

#designpatterns #javascript #modules #nodejs
Рекомендации по теме
Комментарии
Автор

This is not a singleton pattern. Your class constructor should not be accessing "instance" as this breaks encapsulation. Rather you should be handling the singleton exterior to the class (or via static members of that class)

The following achieves singleton exterior to the class (you can write this using static class members however, but usually I prefer to keep instancing entirely separate)

let instance = DBConnection | undefined // exterior
function getDBConnection(): DBConnection {
if(instance) return instance
instance = new DBConnection()
return instance
}

const singleton = getDBConnection()

The reason you should do it this way is because a Singleton of today may need to be multiple instances tomorrow. By embedding the instance in the classes constructor, you've basically said "this class can only ever be singleton", which also breaks encapsulation because it requires the class to know internally how the caller will instance it externally.

Generally if you're writing singletons in the way you are in the video, you might be better off just writing function exports on a module (as modules are singleton)

BinaryReader
visit shbcf.ru