Swift设计模式入门教程:从零掌握iOS开发核心架构
前言:为什么设计模式如此重要?
在iOS开发中,你是否曾经遇到过这样的困境:
- 代码越来越臃肿,难以维护和扩展
- 同样的功能在不同地方重复实现,修改时处处需要调整
- 新成员接手项目时,需要花费大量时间理解代码结构
- 业务逻辑和界面代码混杂在一起,测试困难
设计模式(Design Patterns)正是解决这些问题的金钥匙!它们是被反复验证的、针对特定问题的优雅解决方案模板。本文将带你全面掌握Swift中的23种经典设计模式。
📚 设计模式三大分类
1. 创建型模式(Creational Patterns)
负责对象创建机制,增加创建逻辑的灵活性
2. 结构型模式(Structural Patterns)
关注类和对象的组合,形成更大的结构
3. 行为型模式(Behavioral Patterns)
处理对象间的通信和责任分配
🏗️ 创建型模式详解
单例模式(Singleton) - 确保全局唯一实例
final class AppSettings {
static let shared = AppSettings()
private init() {
// 私有初始化方法确保只有一个实例
}
var theme: String = "dark"
var language: String = "zh-CN"
}
// 使用示例
AppSettings.shared.theme = "light"
print(AppSettings.shared.language) // 输出: zh-CN
适用场景:
- 配置管理类
- 日志记录器
- 数据库连接池
- 缓存管理器
工厂方法模式(Factory Method) - 灵活的对象创建
protocol Vehicle {
func drive()
}
class Car: Vehicle {
func drive() { print("驾驶汽车") }
}
class Bike: Vehicle {
func drive() { print("骑自行车") }
}
class VehicleFactory {
enum VehicleType {
case car, bike
}
static func createVehicle(type: VehicleType) -> Vehicle {
switch type {
case .car: return Car()
case .bike: return Bike()
}
}
}
// 使用示例
let car = VehicleFactory.createVehicle(type: .car)
car.drive() // 输出: 驾驶汽车
🏛️ 结构型模式实战
适配器模式(Adapter) - 接口转换的桥梁
// 旧系统接口
class OldPaymentSystem {
func processPayment(amount: Double) -> String {
return "处理支付: \(amount)元"
}
}
// 新系统期望的接口
protocol NewPaymentProtocol {
func pay(amount: Double) -> String
}
// 适配器类
class PaymentAdapter: NewPaymentProtocol {
private let oldSystem = OldPaymentSystem()
func pay(amount: Double) -> String {
return oldSystem.processPayment(amount: amount)
}
}
// 使用示例
let adapter = PaymentAdapter()
print(adapter.pay(amount: 100.0)) // 输出: 处理支付: 100.0元
装饰器模式(Decorator) - 动态扩展功能
protocol Coffee {
func cost() -> Double
func description() -> String
}
class SimpleCoffee: Coffee {
func cost() -> Double { return 5.0 }
func description() -> String { return "简单咖啡" }
}
class CoffeeDecorator: Coffee {
private let decoratedCoffee: Coffee
init(_ coffee: Coffee) {
self.decoratedCoffee = coffee
}
func cost() -> Double { return decoratedCoffee.cost() }
func description() -> String { return decoratedCoffee.description() }
}
class MilkDecorator: CoffeeDecorator {
override func cost() -> Double { return super.cost() + 2.0 }
override func description() -> String { return super.description() + ", 加牛奶" }
}
class SugarDecorator: CoffeeDecorator {
override func cost() -> Double { return super.cost() + 1.0 }
override func description() -> String { return super.description() + ", 加糖" }
}
// 使用示例
var coffee: Coffee = SimpleCoffee()
coffee = MilkDecorator(coffee)
coffee = SugarDecorator(coffee)
print(coffee.description()) // 输出: 简单咖啡, 加牛奶, 加糖
print("总价: \(coffee.cost())元") // 输出: 总价: 8.0元
🎯 行为型模式精讲
观察者模式(Observer) - 实现数据监听
protocol PropertyObserver: AnyObject {
func propertyDidChange(_ propertyName: String, newValue: Any?)
}
class UserData {
private var observers = [PropertyObserver]()
var username: String = "" {
didSet {
notifyObservers(propertyName: "username", newValue: username)
}
}
var age: Int = 0 {
didSet {
notifyObservers(propertyName: "age", newValue: age)
}
}
func addObserver(_ observer: PropertyObserver) {
observers.append(observer)
}
func removeObserver(_ observer: PropertyObserver) {
observers.removeAll { $0 === observer }
}
private func notifyObservers(propertyName: String, newValue: Any?) {
observers.forEach {
$0.propertyDidChange(propertyName, newValue: newValue)
}
}
}
class ProfileViewController: PropertyObserver {
func propertyDidChange(_ propertyName: String, newValue: Any?) {
print("属性 \(propertyName) 已更新: \(newValue ?? "nil")")
}
}
// 使用示例
let userData = UserData()
let profileVC = ProfileViewController()
userData.addObserver(profileVC)
userData.username = "张三" // 输出: 属性 username 已更新: 张三
userData.age = 25 // 输出: 属性 age 已更新: 25
策略模式(Strategy) - 算法族封装
protocol SortingStrategy {
func sort(_ array: [Int]) -> [Int]
}
class BubbleSort: SortingStrategy {
func sort(_ array: [Int]) -> [Int] {
var arr = array
for i in 0..<arr.count {
for j in 1..<arr.count-i {
if arr[j] < arr[j-1] {
arr.swapAt(j, j-1)
}
}
}
return arr
}
}
class QuickSort: SortingStrategy {
func sort(_ array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let pivot = array[array.count/2]
let less = array.filter { $0 < pivot }
let equal = array.filter { $0 == pivot }
let greater = array.filter { $0 > pivot }
return sort(less) + equal + sort(greater)
}
}
class Sorter {
private var strategy: SortingStrategy
init(strategy: SortingStrategy) {
self.strategy = strategy
}
func setStrategy(_ strategy: SortingStrategy) {
self.strategy = strategy
}
func sort(_ array: [Int]) -> [Int] {
return strategy.sort(array)
}
}
// 使用示例
let numbers = [64, 34, 25, 12, 22, 11, 90]
let bubbleSorter = Sorter(strategy: BubbleSort())
print("冒泡排序: \(bubbleSorter.sort(numbers))")
let quickSorter = Sorter(strategy: QuickSort())
print("快速排序: \(quickSorter.sort(numbers))")
📊 设计模式选择指南
| 场景需求 | 推荐模式 | 优点 |
|---|---|---|
| 全局配置管理 | 单例模式 | 确保唯一实例,全局访问 |
| 对象创建复杂 | 工厂模式 | 封装创建逻辑,解耦调用方 |
| 接口不兼容 | 适配器模式 | 实现接口转换,重用现有代码 |
| 动态功能扩展 | 装饰器模式 | 运行时添加功能,避免子类爆炸 |
| 数据变化监听 | 观察者模式 | 实现松耦合,支持多观察者 |
| 算法灵活切换 | 策略模式 | 算法独立,易于扩展和测试 |
🚀 实战项目:电商应用设计模式应用
购物车系统实现
// 策略模式:折扣计算
protocol DiscountStrategy {
func calculateDiscount(amount: Double) -> Double
}
class NoDiscount: DiscountStrategy {
func calculateDiscount(amount: Double) -> Double { return 0 }
}
class PercentageDiscount: DiscountStrategy {
let percentage: Double
init(percentage: Double) { self.percentage = percentage }
func calculateDiscount(amount: Double) -> Double { return amount * percentage / 100 }
}
class FixedDiscount: DiscountStrategy {
let amount: Double
init(amount: Double) { self.amount = amount }
func calculateDiscount(amount: Double) -> Double { return self.amount }
}
// 观察者模式:库存通知
protocol StockObserver: AnyObject {
func stockUpdated(productId: String, newStock: Int)
}
class ShoppingCart {
private var items: [String: Int] = [:]
private var discountStrategy: DiscountStrategy = NoDiscount()
private var observers: [StockObserver] = []
func setDiscountStrategy(_ strategy: DiscountStrategy) {
discountStrategy = strategy
}
func addObserver(_ observer: StockObserver) {
observers.append(observer)
}
func addItem(_ productId: String, quantity: Int) {
items[productId, default: 0] += quantity
notifyStockChange(productId: productId)
}
func getTotal() -> Double {
let subtotal = items.values.reduce(0.0) { $0 + Double($1) * 10.0 } // 假设每个商品10元
let discount = discountStrategy.calculateDiscount(amount: subtotal)
return subtotal - discount
}
private func notifyStockChange(productId: String) {
observers.forEach {
$0.stockUpdated(productId: productId, newStock: items[productId] ?? 0)
}
}
}
🎯 学习路线图
💡 最佳实践建议
- 不要过度设计:只在真正需要时使用设计模式
- 保持简单:优先选择简单的解决方案
- 理解原理:不仅要会用,更要理解为什么用
- 结合Swift特性:充分利用Swift的语言特性
- 代码可读性:确保模式使用不会降低代码可读性
📝 总结
设计模式是Swift开发者必须掌握的核心技能。通过本文的学习,你应该已经:
- ✅ 理解了23种设计模式的基本概念
- ✅ 掌握了常用模式的Swift实现方式
- ✅ 学会了如何在实际项目中应用设计模式
- ✅ 建立了设计模式的选择和使用准则
记住,设计模式不是银弹,而是工具箱中的工具。正确的使用时机和方法才是关键。现在就开始在你的Swift项目中实践这些模式吧!
下一步行动:
- 选择1-2个最常用的模式在现有项目中实践
- 尝试用设计模式重构一段复杂的代码
- 深入学习Swift特有的设计模式实现方式
- 关注代码的可维护性和扩展性
Happy coding! 🚀
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



