# 面向协议的编程思想

URL: https://caijiao.org/swift/08-protocol-oriented/04-protocol-oriented
Source: docs/swift/08-protocol-oriented/04-protocol-oriented.md
Description: 本章介绍 Swift 面向协议的编程思想（POP），强调通过协议定义接口，实现灵活解耦和代码复用的设计理念。

面向协议编程（Protocol-Oriented Programming，POP）是 Swift 的核心设计理念，通过协议定义接口，实现高度灵活和模块化的代码结构。

## 核心理念

- **抽象接口**：协议定义功能契约，描述类型必须实现的方法和属性。
- **解耦合**：使用协议代替具体类型，降低模块间依赖。
- **代码复用**：协议扩展提供默认实现，减少重复代码。
- **多态性**：协议类型支持多种具体实现，增强扩展性。

## 示例

```swift
protocol Drawable {
    func draw()
}

extension Drawable {
    func draw() {
        print("默认绘制行为")
    }
}

struct Circle: Drawable {
    var radius: Double
}

struct Square: Drawable {
    var side: Double
    func draw() {
        print("绘制正方形，边长：\(side)")
    }
}

func render(shape: Drawable) {
    shape.draw()
}

let circle = Circle(radius: 5)
let square = Square(side: 10)

render(shape: circle)  // 输出：默认绘制行为
render(shape: square)  // 输出：绘制正方形，边长：10
````

POP 提倡通过协议设计程序架构，提高代码灵活性、可测试性和维护性。
