Bridge

Do you remember our system structure for car? We have a protocol and different implementations 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.

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.

results matching ""

    No results matching ""