1

什么是正确(最干净和最简洁)的方式PetOwner,可以在程序的任何后期创建新的实例Cat

假设它可以在响应某些异步请求后createAnotherAnimal自行调用,因此在创建时创建所需的尽可能多的实例是不可能的。PetOwnerCatPetOwner

我解决了注入工厂的问题,但我不相信这是解决问题的最佳方法,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())
4

0 回答 0