设计模式优化说明结构
- 设计模式的定义:明确设计模式解决的问题及其核心思想。
- 应用场景:分析模式在实际开发中的适用情况。
- 优缺点:探讨模式的优势与潜在问题。
- Swift 实现:提供具体的代码示例,展示如何使用该模式。
1. 单例模式 (Singleton Pattern)
定义
单例模式确保一个类在全局范围内只有一个实例,并提供一个访问该实例的全局访问点。
应用场景
- 需要共享状态的资源:如数据库连接、日志管理器、配置文件管理。
优缺点
-
优点:
- 提供全局访问点,方便管理共享资源。
- 避免重复实例化,节省系统资源。
-
缺点:
- 难以测试,尤其在单元测试中无法轻松模拟。
- 可能导致类的职责过多,增加复杂性。
Swift 示例
swift
复制代码
class Logger {
static let shared = Logger() // 全局唯一实例
private init() {} // 禁止外部初始化
func log(message: String) {
print("Log: (message)")
}
}
// 使用
let logger1 = Logger.shared
let logger2 = Logger.shared
logger1.log(message: "This is a singleton pattern.")
print(logger1 === logger2) // true,说明是同一个实例
2. 工厂模式 (Factory Pattern)
定义
工厂模式通过一个工厂类或方法,动态决定创建哪种具体类型的对象,避免直接使用类的构造函数。
应用场景
- 创建对象的逻辑复杂,且经常变化。
- 客户端需要与具体类解耦,比如产品、工具等实例化场景。
优缺点
-
优点:
- 隐藏复杂的实例化逻辑,提高代码可维护性和扩展性。
- 遵循开闭原则:可以方便地增加新的类型而不修改现有代码。
-
缺点:
- 增加了类或方法的复杂性。
Swift 示例
swift
复制代码
protocol Shape {
func draw()
}
class Circle: Shape {
func draw() {
print("Drawing a Circle")
}
}
class Square: Shape {
func draw() {
print("Drawing a Square")
}
}
class ShapeFactory {
static func createShape(type: String) -> Shape? {
switch type.lowercased() {
case "circle":
return Circle()
case "square":
return Square()
default:
return nil
}
}
}
// 使用
if let shape = ShapeFactory.createShape(type: "circle") {
shape.draw() // 输出: Drawing a Circle
}
3. 观察者模式 (Observer Pattern)
定义
观察者模式定义了一种一对多的依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知。
应用场景
- 数据驱动的事件通知,如用户界面更新、订阅发布系统。
- 当一个对象的变化需要通知多个对象时。
优缺点
-
优点:
- 支持动态通信,松耦合。
- 易于扩展,新增观察者不会影响主题类的实现。
-
缺点:
- 可能产生性能开销,特别是观察者较多时。
- 可能引发对象间的循环引用。
Swift 示例
swift
复制代码
protocol Observer: AnyObject {
func update(message: String)
}
class NewsAgency {
private var subscribers = [Observer]()
func subscribe(_ observer: Observer) {
subscribers.append(observer)
}
func notify(message: String) {
for subscriber in subscribers {
subscriber.update(message: message)
}
}
}
class Subscriber: Observer {
func update(message: String) {
print("Received news: (message)")
}
}
// 使用
let agency = NewsAgency()
let subscriber1 = Subscriber()
let subscriber2 = Subscriber()
agency.subscribe(subscriber1)
agency.subscribe(subscriber2)
agency.notify(message: "Swift 6 is coming!")
// 输出:
// Received news: Swift 6 is coming!
// Received news: Swift 6 is coming!
4. 策略模式 (Strategy Pattern)
定义
策略模式定义了一系列算法,将每种算法封装起来,并使它们可以互相替换,客户端无需知道具体实现。
应用场景
- 需要多种算法解决同一类问题,如排序、支付方式选择。
- 动态切换算法或行为。
优缺点
-
优点:
- 遵循开闭原则:增加新算法无需修改原有代码。
- 提高代码灵活性,减少重复逻辑。
-
缺点:
- 增加类数量,可能导致系统复杂度提高。
Swift 示例
swift
复制代码
protocol SortStrategy {
func sort(_ data: [Int]) -> [Int]
}
class AscendingSort: SortStrategy {
func sort(_ data: [Int]) -> [Int] {
return data.sorted()
}
}
class DescendingSort: SortStrategy {
func sort(_ data: [Int]) -> [Int] {
return data.sorted(by: >)
}
}
class SortContext {
private var strategy: SortStrategy
init(strategy: SortStrategy) {
self.strategy = strategy
}
func setStrategy(_ strategy: SortStrategy) {
self.strategy = strategy
}
func sort(data: [Int]) -> [Int] {
return strategy.sort(data)
}
}
// 使用
let context = SortContext(strategy: AscendingSort())
print(context.sort(data: [5, 3, 8, 1])) // 输出: [1, 3, 5, 8]
context.setStrategy(DescendingSort())
print(context.sort(data: [5, 3, 8, 1])) // 输出: [8, 5, 3, 1]