Table of Contents
- What is Singleton?
- Implementation.
- When to Use?
- An Anti-pattern?
What is Singleton?
Singleton is a design pattern that falls under the category of creational design patterns. Creational design patterns are associated with the simple creation of objects.
Singleton itself ensures that at any given point during the software's runtime, there should be only one instance of an object. Usually, this object is available to the software, globally.
Implementation
Before we talk about when to use it, let's quickly implement it and then we can try to understand the nitty-gritty details.
class Database {
private static $instance;
private function __construct() {
// Connect to database
}
static function get_instance(): Database {
if (is_null(self::instance)) {
self::instance = new self();
}
return self::instance;
}
}
If you look at the implementation, you see that the constructor is made private in order to prevent you from creating new instances of the class because database connections in a large system may be expensive.
We use private and static variable instance
to store the instance of the Database class.
Using the get_instance
static method, we access the instance of the Database class, if in case the instance does not exist, we make sure that it does and then return the instance of the class.
When to Use?
Use the singleton pattern only when you need an object to have a single instance throughout your software's runtime. From the example above, you can see that a connection to database is usually required only once.
Any other such expensive operations or global configurations should use singleton but beware that singleton is also called, "An Anti-pattern." It should be almost always be avoided.
An Anti-pattern?
Singleton is one of the patterns that is easy to understand and use. Thus, it may encourage engineers (at least new ones) to overuse it. It should be used only if there is no alternative solution.
Singleton also encourages the use of global variables. For any engineer to keep track of global variables, it increases cognitive load for them. Such cognitive load may lead to poor software. More on cognitive load and psychology later.
Besides, singleton is more or less, a unique instance of a global variable. It can introduce unnecessary restrictions, make unit tests a pain since they may rely on inheritance among other things.
Some call singleton pattern an "evil pattern." Design patterns in general are agreed upon solutions to commonly recurring problems. Systems may use it when there is a good reason to do so, thus knowing this pattern is essential.
Top comments (0)