So, pretty simple question. Ignoring the implications of over-use of the singleton pattern. I'm trying to find a reliable singleton patter in Objective-C. I have come across this:
@implementation SomeSingleTonClass static SomeSingleTonClass* singleInstance; + (SomeSingleTonClass*)getInstance { static dispatch_once_t dispatchOnceToken; dispatch_once(&dispatchOnceToken, ^{ singleInstance = [[SomeSingleTonClass alloc] init]; }); return singleInstance; } - (void)someMethodOnTheInstance { NSLog(@"DO SOMET WORK") } @end
This I am fairly happy with but it leads to a lot of this:
[[SomeSingleTonClass getInstance] someMethodOnTheInstance];
My question is, why is this better than a purely static class.
@implementation SomeStaticClass static NSString* someStaticStateVariable; - (id)init { //Don't allow init to initialize any memory state //Perhaps throw an exception to let some other programmer know //not to do this return nil; } + (void)someStaticMethod { NSLog(@"Do Some Work"); }
All you really gain, is mildly cleaner looking method calls. Basically you swap out this:
[[SomeSingleTonClass getInstance] someMethodOnTheInstance];
For this
[SomeStaticClass someStaticMethod];
This is a minor simplification for sure, and you can always store the instance within your class. This is more intellectual curiosity, what Objective-C god am I pissing off by using static classes instead of singletons? I'm sure I can't be the first person to think this, but I promise, I did a duplicate search first. The few answers I found, I felt like were based on older versions of cocoa, because even the discussed singleton patterns seemed to suffer from threading issues.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .
While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues. Singleton Objects stored on heap while static class stored in stack. Singleton Objects can have constructor while Static Class cannot.
The advantage of using a static class is the compiler makes sure that no instance methods are accidentally added. The compiler guarantees that instances of the class cannot be created. A singleton class has a private constructor that prevents the class from being instantiated.
Statics are the metter of classes --> no relation with singleton pattern.
Static class : Used when you want to group together utility methods that are state independent.
Singleton : Used when you have multiple methods that share a state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With