Search code examples
iosobjective-cdesign-patternssingletonnsoperationqueue

Singleton design patterns and Differences between different types?


There are different types of singleton implementation.

First:

static MyGlobalClass *instance = nil;
+(MyGlobalClass*)myinstance
{
@synchronized(self)
{
    if(instance==nil)
    {
        instance= [MyGlobalClass new];
   }
}
return instance;
}

Second:

+(PKShareClass *)sharedInstance
{
static PKShareClass *shaedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    shaedInstance = [[PKShareClass alloc]init];
});

return shaedInstance;}

And finally with

static NSOperationQueue * _connectionQueue = nil;
+ (NSOperationQueue *) connectionQueue{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    if (!_connectionQueue)
    {
        _connectionQueue = [[NSOperationQueue alloc] init];

    }
});
return _connectionQueue;
}

Here my question is what it means when we initialize like first and second ?? And third one with NSOperationQueue. What is the use when we initialize like third one? Hard to find the meaning.


Solution

  • I'm afraid that i can't give you a link which can explain clearly about both 3 way but i will tell you what i understand.

    • First way: You create instance is a static variable of MyGlobalClass class. In myinstance method, you check if instance is initialized or not. If not, initialize instance. After all, return value of instance. Because instance is a static variable of MyGlobalClass so when you call [MyGlobalClass myinstance], it's always one object.
    • Second way: You create shaedInstance is a static variable of method sharedInstance. When you call dispatch_once(&onceToken, the code inside block is called only one time. About dispatch_once, you can take a look here. Because the initialization method is called only one time, shaedInstance is always one object when you return it. Actually, there is no different if shaedInstance is a static variable of PKShareClass class. You can use both 2 ways.
    • Third way: As you can understand after i explain about second way. This way is same like second way when shaedInstance is a static variable of PKShareClass class. But you don't need to check !_connectionQueue inside dispatch_once. Because it runs only one time and grossly it's always nil at the first time. This way can refactor like:

      static NSOperationQueue * _connectionQueue = nil;
      
      + (NSOperationQueue *) connectionQueue{
          static dispatch_once_t onceToken;
          dispatch_once(&onceToken, ^{
              if (!_connectionQueue)
              _connectionQueue = [[NSOperationQueue alloc] init];
          });
          return _connectionQueue;
       }
      

    Hope my answer can help you understand 3 ways easier ;)