国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Protocols/面向協(xié)議編程, DependencyInjection/依賴式注入 的使用

這篇具有很好參考價(jià)值的文章主要介紹了Protocols/面向協(xié)議編程, DependencyInjection/依賴式注入 的使用。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

1. Protocols 定義實(shí)現(xiàn)協(xié)議,面向協(xié)議編碼

? 1.1 創(chuàng)建面向協(xié)議實(shí)例 ProtocolsBootcamp.swift

import SwiftUI

/// 顏色樣式協(xié)議
protocol ColorThemeProtocol {
    var primary: Color { get }
    var secondary: Color { get }
    var tertiary: Color { get }
}

struct DefaultColorTheme: ColorThemeProtocol {
    let primary: Color   = .blue
    let secondary: Color = .white
    let tertiary: Color  = .gray
}

struct AlternativeColorTheme: ColorThemeProtocol {
    let primary: Color   = .red
    let secondary: Color = .white
    let tertiary: Color  = .orange
}

struct AnotherColorTheme: ColorThemeProtocol{
    var primary: Color  = .blue
    var secondary: Color = .red
    var tertiary: Color  = .purple
}

/// 定義按鈕文字協(xié)議
protocol ButtonTextProtocol{
    var buttonText: String { get }
}

protocol ButtonPressedProtocol{
    func buttonPressed()
}

protocol ButtonDataSourceProtocol: ButtonTextProtocol, ButtonPressedProtocol{
}

class DefaultDataSource: ButtonDataSourceProtocol{
    var buttonText: String = "Protocols are awesome!"
    
    func buttonPressed(){
        print("Button was pressed!")
    }
}

class AlternativeDataSource: ButtonTextProtocol{
    var buttonText: String = "Protocols are lame."
}

/// 面向協(xié)議
struct ProtocolsBootcamp: View {
    let colorTheme: ColorThemeProtocol
    let dataSource: ButtonDataSourceProtocol
    
    var body: some View {
        ZStack {
            colorTheme.tertiary
                .ignoresSafeArea()
            Text(dataSource.buttonText)
                .font(.headline)
                .foregroundColor(colorTheme.secondary)
                .padding()
                .background(colorTheme.primary)
                .cornerRadius(10)
                .onTapGesture {
                    dataSource.buttonPressed()
                }
        }
    }
}

struct ProtocolsBootcamp_Previews: PreviewProvider {
    static var previews: some View {
        // DefaultColorTheme / AlternativeColorTheme / AnotherColorTheme
        ProtocolsBootcamp(colorTheme: DefaultColorTheme(), dataSource: DefaultDataSource())
    }
}

? 1.2 效果圖:

Protocols/面向協(xié)議編程, DependencyInjection/依賴式注入 的使用,SwiftUI Advanced Learning,iOS,Swift,UI

2. DependencyInjection 依賴式注入

? 2.1 創(chuàng)建依賴式注入的實(shí)例 DependencyInjectionBootcamp.swift

import SwiftUI
import Combine

// Problems with singletons
// 1. Singleton's are GLOBAL      單例模式是全局的
// 2. Can't customize the init!   不能自定義初始化
// 3. Can't swap out dependencies 不能交換式依賴
struct PostsMode: Identifiable, Codable{
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

/// 定義協(xié)議 數(shù)據(jù)服務(wù)
protocol DataServiceProtocol {
    /// 獲取數(shù)據(jù)
    func getData() -> AnyPublisher<[PostsMode], Error>
}

/// 生產(chǎn)者數(shù)據(jù)服務(wù)
class ProductionDataService: DataServiceProtocol{
    /// 單例 Singleton
   // static let instance = ProductionDataService()
    
    let url: URL
    
    init(url: URL) {
        self.url = url
    }
    
    func getData() -> AnyPublisher<[PostsMode], Error>{
        URLSession.shared.dataTaskPublisher(for: url)
            .map({$0.data})
            .decode(type: [PostsMode].self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
}

/// 模擬請(qǐng)求服務(wù)器返回?cái)?shù)據(jù)
class MockDataService: DataServiceProtocol{
    let testData: [PostsMode]
    
    init(data: [PostsMode]? ) {
        self.testData = data ?? [
            PostsMode(userId: 1, id: 1, title: "One", body: "One"),
            PostsMode(userId: 2, id: 2, title: "Two", body: "Two"),
            PostsMode(userId: 3, id: 3, title: "Three", body: "Three")
        ]
    }
    
    func getData() -> AnyPublisher<[PostsMode], Error> {
        Just(testData)
            .tryMap({ $0 })
            .eraseToAnyPublisher()
    }
}

/// 依賴試
class Dependencies {
    let dataService: DataServiceProtocol
    
    init(dataService: DataServiceProtocol) {
        self.dataService = dataService
    }
}

/// ViewModel
class DependencyInjectionViewModel: ObservableObject{
    @Published var dataArray: [PostsMode] = []
    var cancellables =  Set<AnyCancellable>()
    let dataService: DataServiceProtocol
    
    init(dataService: DataServiceProtocol) {
        self.dataService = dataService
        loadPosts()
    }

    private func loadPosts(){
        dataService.getData()
            .sink { _ in
                
            } receiveValue: {[weak self] returnedPosts in
                self?.dataArray = returnedPosts
            }
            .store(in: &cancellables)
    }
}

/// 依賴注入
struct DependencyInjectionBootcamp: View {
    @StateObject private var vm: DependencyInjectionViewModel
    
    init(dataService: DataServiceProtocol){
        _vm = StateObject(wrappedValue: DependencyInjectionViewModel(dataService: dataService))
    }
    
    var body: some View {
        ScrollView {
            VStack {
                ForEach(vm.dataArray) { post in
                    Text(post.title)
                    Divider()
                }
            }
        }
    }
}

struct DependencyInjectionBootcamp_Previews: PreviewProvider {
    // static let dataService = ProductionDataService(url: URL(string: "https://jsonplaceholder.typicode.com/posts")!)
    static let dataService = MockDataService(data: [
        PostsMode(userId: 12, id: 12, title: "test", body: "test"),
        PostsMode(userId: 123, id: 123, title: "123", body: "123")
    ])
    
    static var previews: some View {
        DependencyInjectionBootcamp(dataService: dataService)
    }
}

? 2.2 效果圖:

Protocols/面向協(xié)議編程, DependencyInjection/依賴式注入 的使用,SwiftUI Advanced Learning,iOS,Swift,UI文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-724513.html

到了這里,關(guān)于Protocols/面向協(xié)議編程, DependencyInjection/依賴式注入 的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring DI簡(jiǎn)介及依賴注入方式和依賴注入類型

    Spring DI簡(jiǎn)介及依賴注入方式和依賴注入類型

    目錄 一、什么是依賴注入 二、依賴注入方式 1. Setter注入 2. 構(gòu)造方法注入 3. 自動(dòng)注入? 三、依賴注入類型 1. 注入bean類型 2. 注入基本數(shù)據(jù)類型 3. 注入List集合 4. 注入Set集合 5. 注入Map集合 6. 注入Properties對(duì)象 往期專欄文章相關(guān)導(dǎo)讀? 1. Maven系列專欄文章 2. Mybatis系列專欄文章

    2024年02月02日
    瀏覽(22)
  • 【ASP.NET Core 基礎(chǔ)知識(shí)】--依賴注入(DI)--什么是依賴注入

    依賴注入(Dependency Injection,簡(jiǎn)稱DI)是一種設(shè)計(jì)模式,用于解耦和管理類之間的依賴關(guān)系。它的核心思想是將原本需要在代碼中顯式創(chuàng)建的依賴關(guān)系,交給外部容器進(jìn)行控制和管理。 具體來(lái)說(shuō),依賴注入的實(shí)現(xiàn)方式是通過(guò)將依賴對(duì)象的創(chuàng)建和維護(hù)責(zé)任轉(zhuǎn)移到外部容器中,使

    2024年01月23日
    瀏覽(89)
  • spring——依賴注入原理及注入方式

    ??1.依賴注入(Dependency Injection,DI) 是一種設(shè)計(jì)模式和編程技術(shù),其原理是將對(duì)象的依賴關(guān)系由外部容器來(lái)管理和注入。它的目的是解耦組件之間的依賴關(guān)系,提高代碼的靈活性、可維護(hù)性和可測(cè)試性。 ??2.依賴注入的原理 是通過(guò)在對(duì)象的構(gòu)造函數(shù)、屬性或方法中注入所依

    2024年02月08日
    瀏覽(27)
  • springIoc依賴注入循環(huán)依賴三級(jí)緩存

    springIoc依賴注入循環(huán)依賴三級(jí)緩存

    理論思想,原來(lái)的對(duì)象是由使用者來(lái)進(jìn)行控制,有了spring之后,可以把整個(gè)對(duì)象交給spring來(lái)幫我們進(jìn)行管理 依賴注入,把對(duì)應(yīng)的屬性的值注入到具體的對(duì)象中,@autowired,populateBean完成屬性的注入 beanFactory,存儲(chǔ)對(duì)象,使用map結(jié)構(gòu)來(lái)存儲(chǔ),在spring中一般存在三級(jí)緩存,singleton

    2024年01月16日
    瀏覽(20)
  • SpringBoot中的依賴注入和自動(dòng)注入

    以下內(nèi)容為本人學(xué)習(xí) Spring Boot的依賴注入和自動(dòng)注入 與ChatGpt提問(wèn)后對(duì)其回答 進(jìn)行部分修改 (有的錯(cuò)誤實(shí)在是離譜 = =)、格式調(diào)整等操作后的答案, 可能對(duì)于其中部分細(xì)節(jié)(是錯(cuò)是對(duì),能力有限有的看不出來(lái) = =),并未做深入探究 ,大家感興趣的話可以自行驗(yàn)證。 依賴注

    2024年02月06日
    瀏覽(51)
  • Spring Boot中的依賴注入和自動(dòng)注入

    以下內(nèi)容為本人學(xué)習(xí) Spring Boot的依賴注入和自動(dòng)注入 與ChatGpt提問(wèn)后對(duì)其回答 進(jìn)行部分修改 (有的錯(cuò)誤實(shí)在是離譜 = =)、格式調(diào)整等操作后的答案, 可能對(duì)于其中部分細(xì)節(jié)(是錯(cuò)是對(duì),能力有限有的看不出來(lái) = =),并未做深入探究 ,大家感興趣的話可以自行驗(yàn)證。 依賴注

    2024年02月06日
    瀏覽(17)
  • Spring:依賴注入的方式(setter注入、構(gòu)造器注入、自動(dòng)裝配、集合注入)

    Spring:依賴注入的方式(setter注入、構(gòu)造器注入、自動(dòng)裝配、集合注入)

    依賴注入的方式有setter注入、構(gòu)造器注入、自動(dòng)裝配、集合注入 首先,Maven項(xiàng)目pom.xml依賴包如下: pom.xml 【注】:上述除spring依賴包之外其他三個(gè)依賴包用于測(cè)試使用。 1. setter注入 先說(shuō)明一下,這里有的文件為Book2Dao(接口)、Book2DaoImpl(Book2Dao接口實(shí)現(xiàn)類)、Book2Service(接口)、

    2024年02月02日
    瀏覽(28)
  • 使用 @Autowired 依賴注入時(shí)警告不建議使用字段注入

    使用 @Autowired 依賴注入時(shí)警告不建議使用字段注入

    在 Spring 中注入依賴時(shí)有 字段注入 、 構(gòu)造器注入 、S etter 方法注入 三種注入方式。 無(wú)法注入 final 字段 在 Spring 2.5 中引入了 @Autowired 注解,它可以對(duì)類成員變量、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作。在成員變量上使用 @Autowired 注解可以進(jìn)行字段注入,如下:

    2024年02月05日
    瀏覽(46)
  • quarkus依賴注入之三:用注解選擇注入bean

    quarkus依賴注入之三:用注解選擇注入bean

    這里分類和匯總了欣宸的全部原創(chuàng)(含配套源碼):https://github.com/zq2599/blog_demos 本文是《quarkus依賴注入》系列的第三篇,前文咱們掌握了創(chuàng)建bean的幾種方式,本篇趁熱打鐵,學(xué)習(xí)一個(gè)與創(chuàng)建bean有關(guān)的重要知識(shí)點(diǎn):一個(gè)接口如果有多個(gè)實(shí)現(xiàn)類時(shí),bean實(shí)例應(yīng)該如何選擇其中的一個(gè)

    2024年02月14日
    瀏覽(23)
  • quarkus依賴注入之四:選擇注入bean的高級(jí)手段

    quarkus依賴注入之四:選擇注入bean的高級(jí)手段

    這里分類和匯總了欣宸的全部原創(chuàng)(含配套源碼):https://github.com/zq2599/blog_demos 本文是《quarkus依賴注入》系列的第四篇,在應(yīng)用中,一個(gè)接口有多個(gè)實(shí)現(xiàn)是很常見的,那么依賴注入時(shí),如果類型是接口,如何準(zhǔn)確選擇實(shí)現(xiàn)呢?前文介紹了五種注解,用于通過(guò)配置項(xiàng)、profile等手

    2024年02月14日
    瀏覽(19)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包