In this article Strategy Design Pattern in Java with Enum I have said that Design Patterns could be implemented in different ways. Well, today I’m going to introduce a way to implement the Singleton Design Pattern, a simple Design Pattern, but very useful in the programming’s world.
First of all, what is this Design Pattern for? So, Singleton Design Pattern is meant to ensure that a class has only an instance and to provide an access global point for that same instance. That 's it.
Here is the Design Patterns’ generic structure.
Participants
-
Singleton class
- defines an Instance operation that allows the clients access to its unique instance.
- Instance is a class operation. may be responsible for creating your own single instance.
It's worth mentioning that Decorator is a design pattern too, but it isn't the focus of this article. However, it’ss understood that in TypeScript a Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression (This’ how Singleton will be applied), where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
The following images show two different ways to implement this pattern using Decorators.
As you can see, the TypeScript Generics feature has been used - common in other languages that support Object Orientation such as Java. It's worth knowing this resource, because it's very useful.
As I said in other articles, there are so many other Design Patterns and I think we must know about them. Well, that's it. See you guys! 👋👨💻
Top comments (0)