Objectively Patterned – Singleton

In this series of blog articles I will try to cover a number of very important software design patterns, that every developer should have in their toolkit. Design patterns are highly reusable solutions to common software design problems. At their core they are just simple code templates that have been designed to help engineers write clean, reusable and easily understandable code. Most, if not all, design patterns apply across all modern object-oriented programming languages. Despite that, I will be using my favourite one, Objective-C, for this series of articles.

In this article we will cover the Singleton pattern.

The Singleton pattern makes sure that only one instance of a class can ever be initialised. This is extremely useful when you need a single global access point to an instance of a class across your system. There are numerous examples of the Singleton pattern used across Cocoa Frameworks. For instance [UIApplication sharedApplication] is an example of a Singleton object.

Let’s assume we are building a download manager. This class allows you to add items to a queue for downloading from a specified URL. You will want the process of downloading to be accessed in global fashion from any part of your application. That way you can provide feedback on completion and progress as well as access for adding items to the queue.

The code below assumes you are familiar with GCD (Grand Central Dispatch), Apple’s concurrent code execution framework for iOS and OS X. You can read more here https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html#//apple_ref/doc/uid/TP40008079-CH1-SW1. Also we will be using Blocks. Blocks are similar to C functions but on steroids! You can read more here https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html.

Take a look at the code below:

@interface DownloadManager : NSObject
        + (DownloadManager *)sharedDownloadManager;
        – (
void)addToDownloadQueueWithUrl:(NSURL *)url;
@end

+ (DownloadManager *)sharedDownloadManager
{
        static DownloadManager *sharedDownloadManager = nil;
        
static dispatch_once_t onceToken;
        
dispatch_once(&onceToken, ^{
                
sharedDownloadManager = [[self alloc]init];
        });
        
return sharedDownloadManager;
}

Let’s break up the above code and see what’s going on:

Firstly we declare a static variable that will hold our instance and make it globally available within our class.

        static DownloadManager *sharedDownloadManager = nil;

Then we declare a static dispatch_once_t variable. This predicate will ensure that our initialisation code will execute once and only once for the lifetime of our application.

Finally we use GCD’s dispatch_once function to execute a block of code that will initialise our instance of sharedDownloadManager. GCD ensures this is done is a thread-safe manner. So next time the [[DownloadManager sharedDownloadManager]is executed it will initialise an instance of our class. Subsequent calls will always return a reference to the previously created instance. You can now safely call any instance function of this class, knowing that you are working against one global instance. Of course you can expand the above code to add your own custom initialisation code as well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s