Saturday, 16 February 2013

Cocoa design pattern: singleton

how the singleton is popular

      Singleton is one of popular design pattern across many frameworks, and here in IOS its one of the framework corner stone, you will see some thing like defaultCenter, mainBundle, shareObject all of theses are representation of singleton in action



how could it be useful

       when you have single object from class, and it will be the only source of information or control, you want to make sure there is only one instance at any time.
in singleton you make a single source that the program components interact with, its an elegant way to handle global values and functions, it's making them in single repository to eliminate conflict

how singleton work

      There are many ways to implement the singleton design, how ever in objctive c there is two common ways to make singleton

Example on singleton

apple give example of singleton pattern, but it make implicit assumptions of the user. like this code
-(id)init
{
if(there is instance)
      return this instance
else
     init new instance and return it
}

The user here must know this class is singleton and calling "init" will return this single instance

another clear method to implement singleton classes can be like this

static singleton sSingleton
@implementation singleton
+(void)initialize
{
NSAssert(self == [singleton class]);
//print some error here
sSingleton = [singleton new];
}
+(singleton*) sharedSingleton
{
return sSingleton;
}
@end

This approach is easy and thread safe as well. and the assertion make sure the user noticed that this is a singleton class and could not be used as a super class as example.

when to use singleton
singleton design pattern is elegant way to handle interaction across iOS application, however don't overuse it. so if you have an object interact with small number of objects that's ok, otherwise if you have object interact with objects over the application scope. its a good practice to use singleton.

No comments:

Post a Comment