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!
Không có nhận xét nào:
Đăng nhận xét