class SingletonExample {
static let shared = SingletonExample()
private init() { }
}
protocol Product {
func use()
}
class ConcreteProductA: Product {
func use() { print("Using Product A") }
}
class ConcreteProductB: Product {
func use() { print("Using Product B") }
}
class Factory {
static func createProduct(type: String) -> Product? {
switch type {
case "A":
return ConcreteProductA()
case "B":
return ConcreteProductB()
default:
return nil
}
}
}
protocol TaskDelegate: AnyObject {
func didCompleteTask()
}
class TaskManager {
weak var delegate: TaskDelegate?
func startTask() {
// 작업 수행
delegate?.didCompleteTask()
}
}
class TaskHandler: TaskDelegate {
func didCompleteTask() {
print("Task completed")
}
}
class NotificationExample {
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: .exampleNotification, object: nil)
}
@objc func handleNotification() {
print("Notification received")
}
}
extension Notification.Name {
static let exampleNotification = Notification.Name("exampleNotification")
}
Swift에서 이와 같은 디자인 패턴을 적용하면 코드의 가독성, 재사용성, 유지보수성이 높아집니다. 각 패턴은 상황에 맞게 유연하게 사용될 수 있으며, 특히 SwiftUI와 Combine을 사용한 MVVM 패턴은 최신 앱 개발에서 많이 채택되고 있습니다.