Skip to content

Instantly share code, notes, and snippets.

View kien-hoang's full-sized avatar

Kien (Bradley) Hoang kien-hoang

View GitHub Profile
/*
Observer Pattern
1. The subscriber is the "observer" object and receives updates.
2. The publisher is the "observable" object and sends updates.
3. The value is the underlying object that's changed.
Reference: https://howtodoinjava.com/design-patterns/behavioral/observer-design-pattern/
*/
import Foundation
@kien-hoang
kien-hoang / observer-pattern.swift
Created February 1, 2023 11:04
Observer Pattern in Swift
/*
Observer Pattern
1. The subscriber is the "observer" object and receives updates. `AppCoordinator`
2. The publisher is the "observable" object and sends updates. `LoginViewController`
3. The value is the underlying object that's changed.
*/
import UIKit
final class AppCoordinator {
init() {
@kien-hoang
kien-hoang / memento-pattern.swift
Last active January 31, 2023 08:06
Memento Pattern in Swift
/*
Memento Pattern
1. The `originator` is the object to be saved or restored.
2. The `memento` represents a stored state.
3. The `caretaker` requests a save from the originator and receives a memento in response.
The caretaker is responsible for persisting the memento and, later on,
providing the memento back to the originator to restore the originator’s state.
*/
protocol Originator {
@kien-hoang
kien-hoang / dispatch-group.swift
Last active January 31, 2023 02:29
How to know when multiple asynchronous works are done?
/*
DispatchGroup
Create a group, register a bunch of `enter` events, `leave` when a task completes
and the group will automatically do code in `notify` block when all work is done
*/
import UIKit
// Example for calling API
func callAPI(delay: Int, completion: @escaping () -> Void) {
@kien-hoang
kien-hoang / builder-pattern.swift
Created January 18, 2023 05:46
builder-pattern.swift
final class URLRequestBuilder {
private var components = URLComponents()
private var httpMethod: String = "GET"
private var headers: [String: String] = [:]
private var body: [String: Any]?
// MARK: - Lifecycle
init(baseUrl: String = "https://api.themoviedb.org") {
components = URLComponents(string: baseUrl)!
protocol Strategy {
func execute(a: Int, b: Int)
}
class ConcreteStrategyAdd: Strategy {
func execute(a: Int, b: Int) {
print("a + b = \(a + b)")
}
}