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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

private init() {
  self.contactsList = []
}
public class func singleton() -> ContactsBook {
  if current == nil {
    current = ContactsBook()
  }

  return current!
}
private static var current: ContactsBook?
public func printContacts() {
  print("Contacts Book has \(contactsList.count) entries")
  contactsList.forEach { contact in
    print(contact.contactInformation(), separator: "\n")
  }
}
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()
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 1 Next: Instruction 2