Singleton Pattern
Introduction
Welcome to the last lesson of Object Oriented Swift. You will learn how to create an object that exists anywhere. The object is like me. There is only one Bob. I’m omnipresent.
Definition of Singleton
A singleton is an object which is instantiated exactly once.
Design Class
Create a class called, AccountManager. It has a static property with an object of the class itself.
1. class AccountManager {
2. static let sharedInstance = AccountManager()
4. var userInfo = (ID: "bobthedev", Password: 01036343984)
6. // Networking: communicating server
7. func network() {
8. // get everything
9. }
11. private init() { }
12. }
The
privateprevents initialization outside of theAccountManagerclass. If you wish to learn more, you may read The Complete Understanding of Access Control in Swift
Access Object
1. AccountManager.sharedInstance.userInfo
2. // (ID "bobthedev", Password 01036343984)
4. // ViewController One
5. AccountManager.sharedInstance.userInfo.ID // "bobthedev"
7. // ViewController Two
8. AccountManager.sharedInstance.userInfo.ID = "bobleesj"
10. // ViewController Three
11. AccountManager.sharedInstance.userInfo.ID // "bobleesj'
In each view controller, you have access to only one AccountManager().
Examples
The iOS ecosystem often use the singleton pattern for developers to access the universal object. A few examples include, UIApplication, UserDefault, NSNotification. If you wish to learn more about these classes, you may sign up for the upcoming course: The UIKit Fundamentals with Bob.
Source Code
2008_singleton_pattern.playground
Resources
The Complete Understanding of Access Control in Swift 3
Conclusion
You’ve learned the definition of Singleton. Again, think of me. There is only one Bob the Developer.
Often developers avoid the singleton pattern at all cost. It exists everywhere, and when you have a number of them, it becomes difficult to track. So, I’d recommend not to overuse the pattern. If you wish to know how to work with UIApplication, UserDefault, and NSNotification along with Protocols, you may sign up for the upcoming course and receive updates from me.
Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.
