The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
Protocols:
protocol Device {
func run()
}
protocol Switch {
var device: Device { get set }
func turnOn()
}
Implementation:
final class SwitchControl: Switch {
var device: Device
func turnOn() {
self.device.run()
}
init(device: Device) {
self.device = device
}
}
final class Light: Device {
func run() {
print("Light turned ON! 💡")
}
}
final class Toster: Device {
func run() {
print("Toster turned ON! 🍞")
}
}
Usage:
let lightControl = SwitchControl(device: Light())
lightControl.turnOn()
let tosterControl = SwitchControl(device: Toster())
tosterControl.turnOn()