• Category: behavioral
  • Type: object
  • Motivation: allow you to switch the algorithm based upon the situation

diagram

do {
    let sedan = Sedan(Simple())
    sedan.applyBrake()

    let sedan2 = Sedan(ABS())
    sedan2.applyBrake()
}
protocol Brake
{
    func brake()
}

class Simple: Brake
{
    func brake()
    {
        print("simple brake applied")
    }
}

class ABS: Brake
{
    func brake()
    {
        print("brake with ABS applied")
    }
}

protocol Car
{
    var brake: Brake { get }
    func applyBrake()
}

extension Car
{
    func applyBrake()
    {
        brake.brake()
    }
}

class Sedan: Car
{
    private(set) var brake: Brake

    init(_ brake: Brake)
    {
        self.brake = brake
    }
}