MST
星途 面试题库

面试题:Swift装饰器模式与协议扩展结合在复杂业务场景中的优化

假设在一个大型iOS项目中,有多个视图组件,每个视图组件都遵循不同的协议,且需要通过装饰器模式添加不同的附加功能,如日志记录、性能监控等。在这种复杂业务场景下,如何优化装饰器模式与协议扩展结合的代码结构,以提高代码的可维护性、可读性和性能?请详细阐述设计思路并给出关键代码示例。
41.6万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 协议抽象:将通用的功能抽象成协议,比如将日志记录和性能监控分别抽象成LoggingPerformanceMonitoring协议。这样可以使不同的视图组件通过遵循这些协议来获得相应功能,而不是直接在视图组件类中实现这些功能,达到解耦的目的。
  2. 装饰器基类:创建一个装饰器基类,所有具体的装饰器都继承自这个基类。这个基类持有被装饰对象的引用,并通过构造函数初始化。这样可以确保所有装饰器都有统一的基础结构。
  3. 协议扩展:利用协议扩展为协议提供默认实现。在协议扩展中实现日志记录、性能监控等具体功能,这样遵循协议的视图组件只需要声明遵循协议,就可以获得这些功能的默认实现。如果有特殊需求,视图组件也可以重写协议扩展中的方法。
  4. 组合优于继承:在装饰器中,通过组合的方式将附加功能添加到被装饰对象上,而不是使用继承。这样可以避免继承带来的类层次结构复杂的问题,并且可以在运行时动态地添加或移除附加功能。

关键代码示例

  1. 协议定义
// 日志记录协议
protocol Logging {
    func log(message: String)
}

// 性能监控协议
protocol PerformanceMonitoring {
    func startPerformanceMonitoring()
    func stopPerformanceMonitoring()
}
  1. 协议扩展
// 日志记录协议扩展
extension Logging {
    func log(message: String) {
        print("Log: \(message)")
    }
}

// 性能监控协议扩展
extension PerformanceMonitoring {
    func startPerformanceMonitoring() {
        print("Performance monitoring started")
    }
    func stopPerformanceMonitoring() {
        print("Performance monitoring stopped")
    }
}
  1. 视图组件协议
protocol ViewComponent {}
  1. 具体视图组件
class ConcreteViewComponent: ViewComponent, Logging, PerformanceMonitoring {}
  1. 装饰器基类
class Decorator: ViewComponent {
    var component: ViewComponent

    init(component: ViewComponent) {
        self.component = component
    }
}
  1. 具体装饰器
class LoggingDecorator: Decorator, Logging {
    override init(component: ViewComponent) {
        super.init(component: component)
    }

    func log(message: String) {
        print("LoggingDecorator: \(message)")
        (component as? Logging)?.log(message: message)
    }
}

class PerformanceMonitoringDecorator: Decorator, PerformanceMonitoring {
    override init(component: ViewComponent) {
        super.init(component: component)
    }

    func startPerformanceMonitoring() {
        print("PerformanceMonitoringDecorator: Monitoring started")
        (component as? PerformanceMonitoring)?.startPerformanceMonitoring()
    }

    func stopPerformanceMonitoring() {
        print("PerformanceMonitoringDecorator: Monitoring stopped")
        (component as? PerformanceMonitoring)?.stopPerformanceMonitoring()
    }
}
  1. 使用示例
let viewComponent = ConcreteViewComponent()
let loggedComponent = LoggingDecorator(component: viewComponent)
let monitoredComponent = PerformanceMonitoringDecorator(component: loggedComponent)

monitoredComponent.startPerformanceMonitoring()
loggedComponent.log(message: "Some action occurred")
monitoredComponent.stopPerformanceMonitoring()

通过以上设计思路和代码示例,可以有效地优化装饰器模式与协议扩展结合的代码结构,提高代码的可维护性、可读性和性能。