Wrapper 理解

274 阅读2分钟

什么是 Wrapper 模式?

Wrapper 模式(也叫装饰器模式)是一种结构性设计模式,允许你通过创建包装器对象来扩展对象的功能,而不用改变原对象的代码。

示例:打印功能包装器

1. 定义一个基本的协议 Component

这个协议可以代表任意的组件,它有一个执行方法 execute()

protocol Component {
    func execute() -> String
}

2. 定义一个具体的组件实现 BasicComponent

这个组件是最简单的实现,它只会返回一个执行的消息。

class BasicComponent: Component {
    func execute() -> String {
        return "BasicComponent executed"
    }
}

3. 定义一个包装器 LoggingWrapper

包装器会包装一个实现了 Component 协议的对象,并在调用原组件方法前后添加额外的行为。

class LoggingWrapper: Component {
    private var wrappedComponent: Component
    
    init(component: Component) {
        self.wrappedComponent = component
    }
    
    func execute() -> String {
        print("Logging: Before execution")
        let result = wrappedComponent.execute()
        print("Logging: After execution")
        return result
    }
}

4. 测试代码:

现在我们可以通过这个包装器来为原始组件 BasicComponent 添加日志记录功能,而无需修改它的实现。

// 创建一个基本组件
let basicComponent = BasicComponent()

// 使用包装器包装基本组件,增加日志记录功能
let wrappedComponent = LoggingWrapper(component: basicComponent)

// 调用包装后的组件
let result = wrappedComponent.execute()
print(result)

输出结果:

Logging: Before execution
BasicComponent executed
Logging: After execution
BasicComponent executed

解释

  1. 原始组件 BasicComponent
    • BasicComponent 是最简单的组件,它只执行并返回一个结果。
  2. 包装器 LoggingWrapper
    • LoggingWrapper 包装了 BasicComponent,通过 wrappedComponent 来调用原始的 execute() 方法。在调用前后,包装器添加了日志记录功能。
  3. 使用包装器
    • 当我们调用 wrappedComponent.execute() 时,首先会打印 "Before execution",然后调用被包装的组件 BasicComponentexecute(),最后再打印 "After execution"。

总结

通过这种方式,Wrapper 模式允许你在不修改原始对象的情况下,为其添加新的功能,比如日志记录、统计等。