Upgrade to Pro — share decks privately, control downloads, hide ads and more …

KotlinにおけるFactoryメソッド実装パターン

doyaaaaaken
September 22, 2021

 KotlinにおけるFactoryメソッド実装パターン

doyaaaaaken

September 22, 2021
Tweet

More Decks by doyaaaaaken

Other Decks in Programming

Transcript

  1. Kotlinʹ͓͚ΔFactoryϝιουͷ ࣮૷ύλʔϯ Server-Side Kotlin Study #2 2021/09/22 খࢁ݈ଠ(Kenta Koyama) @doyaaaaaaken

  2. ࣗݾ঺հ • ࢓ࣄ • גࣜձࣾsmartround ૑ۀϝϯόʔ / CTO • αʔόαΠυKotlinʢKtorʣɾVueJSΛࠓ͸Α͘ॻ͍͍ͯ·͢

    • OSS׆ಈ • kotlin-csvͷ࡞ऀʢ⭐: 300overʣ • KtorɾExposedɾkotest౳΁ͷίϯτϦϏϡʔτ
  3. ࿩͢಺༰ Kotlinʹ͓͚ΔFactoryϝιουͷ࣮૷ύλʔϯ ʹ͍ͭͯ঺հ ࢀߟɿEffective Kotlin ɹɹɹItem33: Consider factory functions instead

    of constructors
  4. ͜ͷൃද಺ʹ͓͚Δ”Factoryϝιου”ͷఆٛ ʰΠϯελϯεੜ੒Λߦ͏ͨΊͷϝιουʱͱ͍͏ఆٛͰଊ͍͑ͯͩ͘͞ ※ GoFʹΑΔσβΠϯύλʔϯͷ”Factoryύλʔϯ”ͱ͸ҟͳΓ·͢ ʰίϯετϥΫλͷ௚઀ݺͼग़͠ʹΑΔΠϯελϯεੜ੒ʱͰ͸ͳ͘ ʰϝιουܦ༝ͰͷΠϯελϯεੜ੒ํ๏ʢʹFactoryϝιουʣʱΛ ࢖͏΂͖࣌ɾ࢖͍ํʹ͍ͭͯͷ঺հͰ͢

  5. ໨࣍ 1. ίϯετϥΫλΑΓFactoryϝιου͕༏Ε͍ͯΔ఺ 5ͭ 2. KotlinͰͷFactoryϝιου࣮૷ͷॻ͖ํ 5ύλʔϯ

  6. ໨࣍ 1. ίϯετϥΫλΑΓFactoryϝιου͕༏Ε͍ͯΔ఺ 5ͭ 2. KotlinͰͷFactoryϝιου࣮૷ͷॻ͖ํ 5ύλʔϯ

  7. ᶃ: ϝιουʹ໊લ͕͚ͭΒΕΔ

  8. ᶄ: ฦΓ஋ΛαϒλΠϓʹͰ͖Δ

  9. ᶅ: ඞͣ͠΋Πϯελϯεੜ੒͠ͳͯ͘ྑ͍

  10. ᶆ: ՄࢹੑΛॊೈʹ੍ޚͰ͖Δ

  11. ᶇ: Ҿ਺Λ޷͖ʹఆٛͰ͖Δ

  12. ͜͜·Ͱͷ·ͱΊ Factoryϝιου͸ίϯετϥΫλͱൺֱͯ͠ॊೈੑ͕ߴ͍ͨΊ έʔεʹԠͯ͡࢖͏͜ͱΛݕ౼͢Δͱྑ͍ <ݸਓతݟղ> • ίϯετϥΫλΛ࢖͏ͱྑ͍έʔε • γϯϓϧ͞Λ௥ٻ͍ͨ͠έʔεʢdata classͰDTO࡞Δ͚ͩͷ࣌ͱ͔యܕྫʣ •

    FactoryϝιουΛ࢖͏ͱྑ͍έʔε • ॊೈੑΛ΋͍ͨͤͨέʔε • Πϯελϯεੜ੒ํ๏͕ෳ਺ύλʔϯ͋ΔέʔεʢηΧϯμϦίϯετϥΫλ࢖͏ΑΓ͸Factoryϝιουͷ΄͏໊͕લͱ ͔͔Βҙਤ͕Θ͔Γ΍͍͢ʣ • Πϯελϯεੜ੒ϩδοΫ͕ෳࡶͳέʔεʢͦ΋ͦ΋ίϯετϥΫλͩͱ࣮ݱͰ͖ͳ͍έʔεʣ • Πϯελϯεੜ੒ํ๏Λ͋Δఔ౓੍ݶ͍ͨ͠έʔεʢίϯετϥΫλͩͱࣗ༝౓͕ߴ͗͢Δͱײ͡Δέʔεʣ
  13. ໨࣍ 1. ίϯετϥΫλΑΓFactoryϝιου͕༏Ε͍ͯΔ఺ 5ͭ 2. KotlinͰͷFactoryϝιου࣮૷ͷॻ͖ํ 5ύλʔϯ

  14. ᶃ Companion Object Factory Function • Javaͷstaticؔ਺ͱࣅ͍ͯΔҰ൪ΦʔιυοΫεͳॻ͖ํ

  15. ᶄ Top-Level Factory Function • listOf, mapOfͱ͔͸͜ͷύλʔϯ • publicʹͯ͠ϓϩδΣΫτશମͰ࢖͏utilityؔ਺ʹ΋ •

    privateʹͯ͠ϑΝΠϧ಺ͰͷΈ༗ޮͳFactoryؔ਺ʹ΋
  16. ᶅ Extension Factory Function • companion object͕ʢྫ͑͹ϥΠϒϥϦ಺ʹ͋ΔͳͲͯ͠ʣमਖ਼Ͱ͖ͳ͍ ͱ͖ʹ༗༻

  17. ᶆ Fake Constructors

  18. ᶇ Methods on Factory Class • ͍ΘΏΔBuilderύλʔϯ • KotlinͩͱBuilderύλʔϯΛ࢖͏΂͖έʔε͸গͳ͍ʢ໊લ෇͖Ҿ਺ɾσϑΥϧτҾ਺Ͱ୅ସՄೳʣ

  19. ݸਓతݟղ • جຊతʹ͸ύλʔϯᶃɾᶄͷΈͰे෼ • ଞͷύλʔϯ͸಄ͷମૢ • ʰͲͷύλʔϯʹ͢Δ͔ʱΑΓ΋ ʰίϯετϥΫλʹ͢Δ͔Factoryϝιουʹ͢Δ͔ʱͷ΄͏͕େࣄ

  20. ձࣾએ఻ smartroundͰ͸ݱࡏΤϯδχΞΛઈࢍืू͍ͯ͠·͢ʂʢ˞෭ۀՄɾϑϧϦϞʔτʣ ࿩͚ͩฉ͖͍ͨํ΋େ׻ܴͳͷͰWantedlyɾTwitter DM͔Β͓ؾܰʹ͝Ԡื͍ͩ͘͞ʂ ɾελʔτΞοϓ1,800ࣾɾ౤ࢿՈ100͕ࣾར༻ ɾKotlinɾVue.jsɾAWSΛར༻ ɾࣾһ਺10໊௒ͷϑΣʔζͰݱࡏੵۃ࠾༻த

  21. ͝ਗ਼ௌ͋Γ͕ͱ͏͍͟͝·ͨ͠ @doyaaaaaken