Junior — Middle
Explain the Singleton pattern concept and its main features.
sobes.tech AI
Answer from AI
The pattern Singleton guarantees that a class has only one instance and provides a global access point to it. This is useful for managing centralized states or resources, such as application settings or database managers.
Main features of Singleton:
- Single instance: the class controls the creation of the object and prevents creating more than one.
- Global accessibility: the instance is accessible from anywhere in the program via a static method or property.
- Lazy initialization: the object is created upon first access.
Example implementation of Singleton in Dart (Flutter):
class Singleton {
Singleton._privateConstructor();
static final Singleton _instance = Singleton._privateConstructor();
factory Singleton() {
return _instance;
}
void someMethod() {
print('Calling Singleton method');
}
}
void main() {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2)); // true
}
Here, the constructor is private, and access to the instance is through a factory constructor that always returns the same object.