通过策略实现组合
Coddy 面向 C# 开发者的 Swift 课程的第 38 课,共 48 课。
C# 的依赖注入通常会将接口实现存储在对象中。Swift 也可以用类似的方式存储 any Protocol,并调用其要求的行为。这就是组合:外围类型会委托工作,而不是继承某个特定实现。协议存在类型既可以存储值类型的遵循者,也可以存储类的遵循者。在这个示例中,控制台显示器使用注入的文本装饰器。它的操作不同于根据价格策略计算发票单价。保持协议精简,能让测试更容易提供替代实现,也能避免调用方依赖某个具体遵循者独有的字段。
C#
完整程序文件:Program.cs。
using System;
using System.Collections.Generic;
using System.Linq;
interface IDecorator { string Wrap(string text); }
sealed class Brackets : IDecorator { public string Wrap(string text) { return "[" + text + "]"; } }
sealed class Display { private readonly IDecorator decorator; public Display(IDecorator decorator) { this.decorator = decorator; } public string Render(string text) { return decorator.Wrap(text); } }
class Program
{
static void Main()
{
var display = new Display(new Brackets());
Console.WriteLine(display.Render("news"));
}
}Swift
完整程序文件:Decorator.swift。
protocol Decorator { func wrap(_ text: String) -> String }完整程序文件:Brackets.swift。
struct Brackets: Decorator { func wrap(_ text: String) -> String { "[" + text + "]" } }完整程序文件:Display.swift。
struct Display {
let decorator: any Decorator
func render(_ text: String) -> String { decorator.wrap(text) }
}完整程序文件:main.swift。
let display = Display(decorator: Brackets())
print(display.render("news"))挑战
简单实现 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") }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器