The aim of this post is to present Singleton design pattern in a template. I have seen some post and articles that showed the implementation key points separately, so this is why I have decided to write a mini-post showing an implementation template and its usage.
First of all, let’s define what a Singleton pattern is:
...the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects…. (Wikipedia)
Pattern implementation
This is my singleton implementation class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#import "MySingletonClass.h" @implementation MySingletonClass{ int iLocalAttribute; } -(id) init{ if([super init]){ iLocalAttribute=5; } return self; } + (MySingletonClass*)sharedInstance { static MySingletonClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[MySingletonClass alloc] init]; // Do any other initialisation stuff here }); return sharedInstance; } -(int) giveMe5{ iLocalAttribute+=5; return iLocalAttribute; } @end |
I have added a local attribute (iLocalAttribute
), for showing how to handle them, at the beginning I had to create them as static and for having access to them I had also to create static methods, but in a few lines I will explain how to avoid that.
The key point is the sharedInstance method:
- Declare a static variable to hold the instance of the class, ensuring it’s always available, but inside of
sharedInstance
method context. -
dispatch_once_t
which ensures that the initialization code executes only once. - Instance of
MySingletonClass
. - Finally return the instance class.
Finally I have created a simple function that updates the local attribute and returns its value. As you can see neither the attribute nor the method are static.
This is the header class:
1 2 3 4 5 6 7 8 |
#import <Foundation/Foundation.h> @interface MySingletonClass : NSObject + (MySingletonClass*)sharedInstance; -(int) giveMe5; @end |
Pattern usage
This is my singleton implementation class:
1 |
NSLog(@"%d",[[MySingletonClass sharedInstance] giveMe5]); |