? 桥接(结构型模式)
桥接模式将抽象部分与实现部分分离,使它们都可以独立的变化。
示例:
protocol Switch {
var appliance: Appliance { get set }
func turnOn()
}
protocol Appliance {
func run()
}
final class RemoteControl: Switch {
var appliance: Appliance
func turnOn() {
self.appliance.run()
}
init(appliance: Appliance) {
self.appliance = appliance
}
}
final class TV: Appliance {
func run() {
print("tv turned on");
}
}
final class VacuumCleaner: Appliance {
func run() {
print("vacuum cleaner turned on")
}
}
用法
let tvRemoteControl = RemoteControl(appliance: TV())
tvRemoteControl.turnOn()
let fancyVacuumCleanerRemoteControl = RemoteControl(appliance: VacuumCleaner())
fancyVacuumCleanerRemoteControl.turnOn()