Object-Oriented Programming: Beyond the Basics

Oct 17 2023 · Swift 5.9, iOS 17, Xcode 15

Lesson 03: Design Patterns

Demo 1

Episode complete

Play next episode

Next
Transcript

In this demo, you’ll get to know the first design pattern: the Singleton. Start by opening the starter playground. In the navigator, look in the Sources folder and open ContactsBook.swift.

You intended your team members to use the static property directly and never initialize a new instance. However, that’s a big assumption. Instead, you’ll enforce your intention in the implementation.

First, you’ll make the initializer a private method so no one can access it:

private init() {
  self.contactsList = []
}

You don’t want to expose the internal details about the static property, so you’ll create a new method that replaces the constructor. This will be the method that’s also responsible for returning the instance to be used.

You’ll construct the static property, if it has never been created before, then return it. To do so, add this new method right after the private constructor:

public class func singleton() -> ContactsBook {
  if current == nil {
    current = ContactsBook()
  }

  return current!
}

Update current to the following:

private static var current: ContactsBook?

This makes ContactsBook an optional, meaning it may or may not contain a value.

You need just one more method to print out the contents of the contacts book. Add the following:

public func printContacts() {
  print("Contacts Book has \(contactsList.count) entries")
  contactsList.forEach { contact in
    print(contact.contactInformation(), separator: "\n")
  }
}

Return to the main playground. Delete all the code that used ContactsBook before, then add the following:

let book1 = ContactsBook.singleton()
let book2 = ContactsBook.singleton()
let book3 = ContactsBook.singleton()
let book4 = ContactsBook.singleton()

book1.saveContact(contact: ehabContact)
book2.saveContact(contact: timContact)
book3.saveContact(contact: kodeco)
book4.saveContact(contact: razeware)

... // Adding the relationships

book1.printContacts()

Here, you’ve created four different properties for the contacts book, each from singleton(). You then added a different contact to each instance.

Run the program. You’ll see that calling book1 printed all four contacts as if they were all added to it. The reality is that all four instances are actually the same instance. It’s now impossible to create a second instance of ContactsBook.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 1 Next: Instruction 2