Singleton Pattern
Nguy?n ??ng Khoa
??Fullstack Developer | PHP | ReacJS | NodeJS | SQL | Database??
Quay tr? l?i series design patterns, ngày h?m nay t?i s? chia s? t?i các b?n Singleton Pattern.
Cùng tìm hi?u nhé.
---- Singleton Pattern ----
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this?instance.
?? Problem
The Singleton pattern solves two problems at the same time, violating the Single Responsibility Principle:
Here’s how it works: imagine that you created an object, but after a while decided to create a new one. Instead of receiving a fresh object, you’ll get the one you already created.
Note that this behavior is impossible to implement with a regular constructor since a constructor call must always return a new object by design.
Just like a global variable, the Singleton pattern lets you access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.
There’s another side to this problem: you don’t want the code that solves problem #1 to be scattered all over your program. It’s much better to have it within one class, especially if the rest of your code already depends on it.
Nowadays, the Singleton pattern has become so popular that people may call something a singleton even if it solves just one of the listed problems.
?? Solution
All implementations of the Singleton have these two steps in common:
If your code has access to the Singleton class, then it’s able to call the Singleton’s static method. So whenever that method is called, the same object is always returned.
?Applicability
Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.
The Singleton pattern disables all other means of creating objects of a class except for the special creation method. This method either creates a new object or returns an existing one if it has already been created.
Use the Singleton pattern when you need stricter control over global variables.
Unlike global variables, the Singleton pattern guarantees that there’s just one instance of a class. Nothing, except for the Singleton class itself, can replace the cached instance.
Note that you can always adjust this limitation and allow creating any number of Singleton instances. The only piece of code that needs changing is the body of the getInstance method.