Junior — Middle
What methods can be used to implement the Singleton pattern in programming?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it. In iOS (Swift/Objective-C), there are several ways to implement Singleton:
- Using a static constant (Swift)
class MySingleton {
static let shared = MySingleton()
private init() { }
}
This method is lazy and thread-safe because static let is initialized once.
- Using dispatch_once (Objective-C)
+ (instancetype)sharedInstance {
static MySingleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- Lazy initialization with check (not recommended due to thread safety issues)
class MySingleton {
static var shared: MySingleton = {
return MySingleton()
}()
private init() { }
}
- Using enum (Swift)
enum MySingleton {
static let shared = MySingleton()
}
But most often, the first method with static let is used.
Important: the constructor should be private to prevent creating other instances.