在这种情况下,注入工厂是否有意义(Swinject)

时间:2016-04-26 09:23:39

标签: swift dependency-injection swinject

PetOwner能够在程序的任何后期创建Cat的新实例的正确(最简洁,最简洁)的方法是什么?

我们假设createAnotherAnimal在获得对某些异步请求的响应后可以调用PetOwner,因此在创建Cat时会根据需要创建PetOwner个实例。 1}}是不可能的。

我解决了注入工厂的问题,但我不相信这是解决问题的最佳方法,Swinject有哪些替代方案?

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

class Cat: AnimalType {
    var name: String?

    init(name: String?) {
        self.name = name
    }

    func sound() -> String {
        return "Meow!"
    }
}

protocol PersonType {
    func play() -> String
    func createAnotherAnimal() -> Void
}

class PetOwner: PersonType {
    var pets: [AnimalType] = []
    let petFactory : AnimalFactory

    init(petFactory : AnimalFactory) {
        self.petFactory = petFactory
    }

    func createAnotherAnimal() {

        let pet = petFactory.factoryMethod()
        self.pets.append(pet)
    }

    func play() -> String {
        if(pets.count>0) {
            let pet : AnimalType = pets[0];
            let name = pet.name ?? "someone"
            return "I'm playing with \(name). \(pet.sound())"
        } else {
            return "No animals"
        }
    }
}

class AnimalFactory {
    let factoryMethod : () -> AnimalType

    init(factoryMethod: () -> AnimalType) {
        self.factoryMethod = factoryMethod
    }
}

// Create a container and register service and component pairs.
let container = Container()
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
container.register(PersonType.self) { r in PetOwner(petFactory: r.resolve(AnimalFactory.self)!) }

container.register(AnimalFactory.self){r in AnimalFactory(factoryMethod:{ () -> AnimalType in r.resolve(AnimalType.self)!}) }

// The person is resolved to a PetOwner with a Cat.
let person = container.resolve(PersonType.self)!

person.createAnotherAnimal()

print(person.play())

0 个答案:

没有答案