Swift World: Design Patterns — Bridge

Peng
SwiftWorld
Published in
2 min readMar 14, 2017

Do you remember our system structure for car? We have a protocol and different implements like the code below.

protocol Car {
func drive()
}
class Sedan: Car {
func drive() {
print("drive a sedan")
}
}
class SUV: Car {
func drive() {
print("drive a SUV")
}
}

Then what if we want to describe colored cars? This requirement add another variable in current structure. Normally, we need to add a inheritance level.

class RedSedan: Sedan {
func drive() {
print("drive a red sedan")
}
}

The structure is in the below figure

Its disadvantage is too many inheritance levels. If we want to add new colors or new car types, the whole structure will becomes more complicated.

Let’s refactor with bridge pattern. The following figure depicts its structure.

From Bridge pattern — Wikipedia
protocol ColoredCar {
var car: Car { get set }
func drive()
}
class RedCar: ColoredCar {
var car: Car
init(car: Car) {
self.car = car
}
func drive() {
car.drive()
print("It's red.")
}
}
//usage
let sedan = Sedan()
let redSedan = RedCar(car: sedan)
redSedan.drive()

New structure is in the following figure.

Then there is no so many inheritances. The car and color will be scaled respectively.

Thanks for your time. Please clap to get this article seen by more people. Please follow me by clicking Follow. As a passionate iOS developer, blogger and open source contributor, I’m also active on Twitter and GitHub.

--

--

Peng
SwiftWorld

Engineers are the artists of our generation.