Swift 高级设计模式:从理论到实践
设计模式不仅仅是抽象概念,而是经过时间验证的常见问题解决方案。如果你已经掌握了基础模式(Singleton、Delegate、MVC)并正在开发复杂的 iOS/macOS 应用程序,那么是时候进入下一个阶段了。在本文中,我们将深入探讨四种高级模式:Builder、Strategy、Observer(通过 Combine)和 Coordinator。每种模式都将通过真实的 Swift 代码和集成到现有项目中的技巧进行说明。
1. Builder(建造者)——灵活配置复杂对象
Builder 模式非常适合创建具有多个可选参数的对象。您无需使用包含数十个参数的长初始化器,而是采用逐步构建的方式。
示例:配置 UIAlertController
class AlertBuilder { private var title: String? private var message: String? private var actions: [UIAlertAction] = [] private var preferredStyle: UIAlertController.Style = .alert
func setTitle(_ title: String) -> AlertBuilder { self.title = title return self }
func setMessage(_ message: String) -> AlertBuilder { self.message = message return self }
func addAction(title: String, style: UIAlertAction.Style = .default, handler: ((UIAlertAction) -> Void)? = nil) -> AlertBuilder { let action = UIAlertAction(title: title, style: style, handler: handler) actions.append(action) return self }
func setStyle(_ style: UIAlertController.Style) -> AlertBuilder { self.preferredStyle = style return self }
func build() -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) actions.forEach { alert.addAction($0) } return alert }}
// 使用let alert = AlertBuilder() .setTitle("错误") .setMessage("无法加载数据") .addAction(title: "确定", style: .default) .addAction(title: "重试", style: .cancel) .build()present(alert, animated: true)何时使用:在创建配置器、复杂的 ViewController 或具有大量选项的数据模型时。
2. Strategy(策略)——动态切换算法
Strategy 模式允许您将一系列算法封装起来,并使它们可以相互替换。这对于处理支付、数据验证或渲染特别有用。
示例:内容过滤系统
protocol FilterStrategy { func apply(to items: [String]) -> [String]}
class AlphabeticalFilter: FilterStrategy { func apply(to items: [String]) -> [String] { return items.sorted() }}
class LengthFilter: FilterStrategy { func apply(to items: [String]) -> [String] { return items.filter { $0.count > 5 } }}
class ContentManager { private var strategy: FilterStrategy
init(strategy: FilterStrategy) { self.strategy = strategy }
func setStrategy(_ strategy: FilterStrategy) { self.strategy = strategy }
func filter(items: [String]) -> [String] { return strategy.apply(to: items) }}
// 使用let manager = ContentManager(strategy: AlphabeticalFilter())let data = ["Swift", "Objective-C", "Kotlin", "Java", "Python"]print(manager.filter(items: data)) // ["Java", "Kotlin", "Objective-C", "Python", "Swift"]
manager.setStrategy(LengthFilter())print(manager.filter(items: data)) // ["Objective-C", "Python"]提示:将 Strategy 与工厂方法结合使用,以便根据用户设置选择策略。