Menu
CoddyTech

通过策略实现组合

Coddy 面向 Go 开发者的 Swift 课程的第 38 课,共 48 课。

Go 的组合通常会在结构体中存储一个接口值。Swift 也可以将任意 Protocol 存储为存在类型,从而在运行时从符合该协议的类型中进行选择。这两种抽象都能在不要求使用某一种具体表示的情况下提供行为。

源代码中的 Notice 会委托给 Formatter,Swift 中的 Notice 也一样。也可以采用泛型设计,将具体的 formatter 类型保留为参数。共享和复制的行为仍取决于存储的符合类型包含的是值还是引用。

Go:完整程序

formatter.go

package main
type Formatter interface { Format(string) string }

brackets.go

package main
type Brackets struct{}
func (Brackets) Format(text string) string { return "[" + text + "]" }

notice.go

package main
type Notice struct { Formatter Formatter }
func (notice Notice) Render(text string) string { return notice.Formatter.Format(text) }

main.go

package main
import (
    "fmt"
)

func main() {
notice := Notice{Formatter: Brackets{}}
    fmt.Println(notice.Render("ready"))
}

Swift:完整程序

Formatter.swift

import Foundation
protocol Formatter { func format(_ text: String) -> String }

Brackets.swift

import Foundation
struct Brackets: Formatter {
    func format(_ text: String) -> String { "[" + text + "]" }
}

Notice.swift

import Foundation
struct Notice {
    let formatter: any Formatter
    func render(_ text: String) -> String { formatter.format(text) }
}

main.swift

import Foundation
let notice = Notice(formatter: Brackets())
print(notice.render("ready"))

在实现中保留对策略的调用。将其替换为 Brackets 已知的公式,会破坏那些传入其他有效格式化行为的调用方。

challenge icon

挑战

简单

实现 Policy 协议,并实现 charge(for units: Int) -> Int。实现 FlatPolicy(rate:),其收费金额为费率乘以单位数。实现 Invoice(policy:),用于存储任意 Policy,并通过 total(units:) 委托该策略计算总额。自定义策略必须能够正常工作。输入为 0 到 100 之间的费率,以及 0 到 100 之间的单位数。输出发票总额。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印内容。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后恰好添加一个换行符来打印返回的文本。所有数值运算都在 Int 的范围内。

代码应写在 Policy.swift、FlatPolicy.swift、Invoice.swift 和 Functions.swift 中。main.swift 包含提供的输入输出代码,不能编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbePolicy: Policy { func charge(for units: Int) -> Int { units + 9 } }
return FlatPolicy(rate: 7).charge(for: 3) == 21 && Invoice(policy: ProbePolicy()).total(units: 4) == 13 && Invoice(policy: FlatPolicy(rate: 2)).total(units: 5) == 10
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器