lundi 25 septembre 2017

Strategy design pattern in swift

I am currently learning design patterns with the Head First Design Patterns: A Brain-Friendly Guide book. I was trying to replicate their java code onto swift code like so:

protocol Flyable: class {
    func fly()
}

class Duck {

    weak var flyBehavior: Flyable?

    func fly() {
        flyBehavior?.fly()
    }
}

class MallardDuck: Duck {

    func LoadBehaviors() {
        self.flyBehavior = FlyWithJet()
    }
}

class FlyWithJet: Flyable {

    func fly() {
        print("Fly with a jet on my back!")
    }
}

class FlyWithWings: Flyable {
    func fly() {
        print("Fly with my wings!")
    }
}

let md = MallardDuck()
md.LoadBehaviors()
md.fly() //*Nothings*

I have a super class called Duck and MallardDuck inherits from it. In my Duck class, I have a fly() method and the implementation of it is delegated out to a class that conforms to the flyable protocol. Howcome, in the MallardDuck class, when I assign my flying behavior to FlyWithJet(), and when I call the fly() method on MallardDuck, I got a nil back?

Any feedbacks are welcome!

Aucun commentaire:

Enregistrer un commentaire