📦 依赖容器 (Yīlài Róngqì)

License: MIT Static Badge

什么是依赖容器 (Shénme shì Yīlài Róngqì)

旨在确保多个对象依赖于单个容器来管理所有依赖项。(Zhǐ zài quèbǎo duō gè duìxiàng yīlài yú dān gè róngqì lái guǎnlǐ suǒyǒu yīlài xiàng.)

✔️ 示例 (Shìlì)

struct ContentView: View {
    
    let container: Container
    var a_service: A_Serviceable { container.resolve() }
    var b_service: B_Serviceable { container.resolve() }
    
    init(container: Container = .live) {
        self.container = container
    }
    
    var body: some View {
        Button("Fetch A Service") {
            a_service.fetch()
        }
        Button("Fetch B Service") {
            b_service.fetch()
        }
    }
}

extension Container {

    static let live = Container()
        .register { A_Service() as A_Serviceable }
        .register { B_Service() as B_Serviceable }
        
    static let fake = Container()
        .register { FakeA_Serivce() as A_Serviceable }
        .register { FakeB_Serivce() as B_Serviceable }
}
protocol A_Serviceable {
    func fetch()
}

protocol B_Serviceable {
    func fetch()
}
struct A_Service: A_Serviceable {
    func fetch() {
        print("A Fetch")
    }
}

struct B_Service: B_Serviceable {
    func fetch() {
        print("B Fetch")
    }
}
struct FakeA_Serivce: A_Serviceable {
    func fetch() -> String {
        "Fake A Fetch"
    }
}

struct FakeB_Serivce: B_Serviceable {
    func fetch() -> String {
        "Fake B Fetch"
    }
}