Implementation

Implementation of the Singleton pattern often typically creates a single object using the factory method, and this instance/object is called a shared instance in most cases. Since the access to the instance is passed on through a class method, the need to create an object is eliminated. Let's look at the Singleton implementation in the code in the following section.

For this exercise, we will use the command line tool Xcode template to create a project and name it Singleton. Our Singleton class will be called SingletonObject, which we will create as a normal Cocoa class, and it will be a subclass of NSObject. The project setup will look like this so far:

Let's add a class method called sharedInstance as discussed earlier, since this is how the class will make the Singleton available. Its return value will be of the SingleObject type, as follows:

func sharedInstance() -> SingletonObject {
}

You will note the compiler error at this time since the function does not return the value as promised in the function signature, but we will change it soon. The function will store the instance in a static local reference called localSharedInstance. Static locals are much like global objects; they retain their value for the lifetime of the application, yet they are limited in scope. These qualities make them ideal to be a Singleton since they are permanent and yet ensure that our Singleton is only available through sharedInstance. This is one of the ways in which our Singleton implementation ensures that the Singleton stays singular. The basic structure of shared instance consists of a conditional block that tests whether a Singleton instance has been allocated, but to your surprise, that's the older way of doing things or may be the way to go in other languages, but in Swift, the implementation has changed to merely one line, and we don't require a method. The implementation looks like this:

class SingletonObject: NSObject {
static let sharedInstance = SingletonObject()
}

Simple, isn't it? In the next section, we will discuss some pros and cons of using the Singleton design pattern.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset