To create a singleton in TypeScript, you can use the object-oriented programming pattern known as the Singleton pattern. This pattern is a creational pattern that ensures that a class has only one instance, and provides a global point of access to that instance.
Here's an example implementation in TypeScript:
index.ts323 chars16 lines
In this implementation, the Singleton
class has a private static property instance
that holds the single instance of the class. The constructor is made private to prevent direct instantiation of the class.
The static method getInstance()
provides global access to the single instance of the class. This method first checks if the instance exists, and if not, creates one.
You can then use the getInstance()
method to access the single instance of the Singleton
class throughout your application:
index.ts48 chars2 lines
Note that this implementation is not thread-safe, which may lead to issues in multi-threaded environments. If you need a thread-safe implementation, you can add a mutex or lock to the getInstance()
method.
gistlibby LogSnag