Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 12, 2016 17:17
Show Gist options
  • Save KentarouKanno/79830c0f16ada1f5dd4d9464532ea222 to your computer and use it in GitHub Desktop.
Save KentarouKanno/79830c0f16ada1f5dd4d9464532ea222 to your computer and use it in GitHub Desktop.
Dependency Injection

Dependency Injection

参考URL:
Dependency Injection Framework for Swift
[Swift] DIって何? 実践編

protocol AnimalType {
    var name: String { get }
    func sound() -> String
}

class Cat: AnimalType {
    let name: String
    
    init(name: String) {
        self.name = name
    }
    
    func sound() -> String {
        return "Meow!"
    }
}

class Dog: AnimalType {
    let name: String
    
    init(name: String) {
        self.name = name
    }
    
    func sound() -> String {
        return "Bow wow!"
    }
}


class PetOwner {
    let pet: AnimalType
    
    init(pet: AnimalType) {
        self.pet = pet
    }
    
    func play() -> String {
        return "I'm playing with \(pet.name). \(pet.sound())"
    }
}

let catOwner = PetOwner(pet: Cat(name: "Kitty"))
print(catOwner.play())
//=> "I'm playing with Kitty. Meow!\n"


let dogOwner = PetOwner(pet: Dog(name: "Rocky"))
print(dogOwner.play())
//=> "I'm playing with Rocky. Bow wow!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment