面试题答案
一键面试- 定义
Shape
协议:
protocol Shape {
func draw()
}
- 定义装饰器协议扩展:
extension Shape {
func drawWithBorder() {
draw()
print("Drawing border around the shape.")
}
}
- 实现具体的
Shape
类型:
struct Circle: Shape {
func draw() {
print("Drawing a circle.")
}
}
- 使用示例:
let circle = Circle()
circle.draw()
circle.drawWithBorder()
在上述代码中,首先定义了Shape
协议,它有一个draw
方法用于绘制形状。然后通过协议扩展为Shape
协议添加了drawWithBorder
方法,该方法在调用原draw
方法后,打印出绘制边框的信息。接着定义了Circle
结构体遵循Shape
协议。最后创建Circle
实例,并分别调用draw
方法和通过协议扩展添加的drawWithBorder
方法,展示装饰器模式与协议扩展结合为类型增强功能的效果。