面试题答案
一键面试设计思路
- 协议抽象:将通用的功能抽象成协议,比如将日志记录和性能监控分别抽象成
Logging
和PerformanceMonitoring
协议。这样可以使不同的视图组件通过遵循这些协议来获得相应功能,而不是直接在视图组件类中实现这些功能,达到解耦的目的。 - 装饰器基类:创建一个装饰器基类,所有具体的装饰器都继承自这个基类。这个基类持有被装饰对象的引用,并通过构造函数初始化。这样可以确保所有装饰器都有统一的基础结构。
- 协议扩展:利用协议扩展为协议提供默认实现。在协议扩展中实现日志记录、性能监控等具体功能,这样遵循协议的视图组件只需要声明遵循协议,就可以获得这些功能的默认实现。如果有特殊需求,视图组件也可以重写协议扩展中的方法。
- 组合优于继承:在装饰器中,通过组合的方式将附加功能添加到被装饰对象上,而不是使用继承。这样可以避免继承带来的类层次结构复杂的问题,并且可以在运行时动态地添加或移除附加功能。
关键代码示例
- 协议定义
// 日志记录协议
protocol Logging {
func log(message: String)
}
// 性能监控协议
protocol PerformanceMonitoring {
func startPerformanceMonitoring()
func stopPerformanceMonitoring()
}
- 协议扩展
// 日志记录协议扩展
extension Logging {
func log(message: String) {
print("Log: \(message)")
}
}
// 性能监控协议扩展
extension PerformanceMonitoring {
func startPerformanceMonitoring() {
print("Performance monitoring started")
}
func stopPerformanceMonitoring() {
print("Performance monitoring stopped")
}
}
- 视图组件协议
protocol ViewComponent {}
- 具体视图组件
class ConcreteViewComponent: ViewComponent, Logging, PerformanceMonitoring {}
- 装饰器基类
class Decorator: ViewComponent {
var component: ViewComponent
init(component: ViewComponent) {
self.component = component
}
}
- 具体装饰器
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()
}
}
- 使用示例
let viewComponent = ConcreteViewComponent()
let loggedComponent = LoggingDecorator(component: viewComponent)
let monitoredComponent = PerformanceMonitoringDecorator(component: loggedComponent)
monitoredComponent.startPerformanceMonitoring()
loggedComponent.log(message: "Some action occurred")
monitoredComponent.stopPerformanceMonitoring()
通过以上设计思路和代码示例,可以有效地优化装饰器模式与协议扩展结合的代码结构,提高代码的可维护性、可读性和性能。