Thứ Ba, 13 tháng 1, 2015

A simple example of Delegate Pattern in Swift

Well, I've just start self learning to program iOS apps using Swift programming language. One early thing that you stumble into when learning it is a concept call "Delegate pattern". It's quite confusing for a self-taught learner like me and I've looked around for a good simple example. In wikipedia, there an article that explain the concept with many languages. However, I don't like the the functions and class names. So I try to rewrite the example which is simpler and funnier. Well, there's ways to go with Swift and iOS, but at least the first steps must be interesting, huh?

protocol AnimalBehavior {
    func eating()
    func calling()
}

class DogBehavior : AnimalBehavior{
    func eating(){
        println("The DOG is eating...")
    }
    func calling(){
        println("Wufff! Wufff!")
    }
}

class CatBehavior : AnimalBehavior{
    func eating(){
        println("The CAT is eating...")
    }
    func calling(){
        println("Meowwwww")
    }
}


class Animal{
    var behavior: AnimalBehavior;
    init(){
        behavior=DogBehavior();
    }
    func eating(){
        behavior.eating()
    }
    func calling(){
        behavior.calling()
    }
    func isACat(){
        behavior=CatBehavior()
    }
    func isADog(){
        behavior=DogBehavior()
    }
    
}


let myPet=Animal() // Notice this is not a variable but const
myPet.isACat();
myPet.calling(); // Meowwwwww
myPet.isADog();

myPet.calling(); // Wufff! Wufff!