๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ—‚๏ธ ์Šคํ„ฐ๋”” ํ™œ๋™/๐Ÿ“— ๋ฉด์ ‘์„ ์œ„ํ•œ CS ์ „๊ณต์ง€์‹ ๋…ธํŠธ

[๋””์ž์ธํŒจํ„ด] MVVM ํŒจํ„ด

by ๐Ÿ’พ๊ณ ๊ตฌ๋งˆ๋ง›ํƒ•๋จน๊ณ ์‹ถ๋‹ค 2024. 9. 9.
728x90

MVVM ํŒจํ„ด

์†Œํ”„ํŠธ์›จ์–ด ๋””์ž์ธ ํŒจ๋˜, UI ๊ฐœ๋ฐœ์— ์‚ฌ์šฉ. ๋ทฐ(View)์™€ ๋ชจ๋ธ(Model) ์‚ฌ์ด์˜ ๊ฐ•ํ•œ ๊ฒฐํ•ฉ์„ ์ค„์ด๊ธฐ ์œ„ํ•ด ๋„์ž…

  • Model : ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๋ฐ์ดํ„ฐ์™€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๊ด€๋ฆฌ
  • View : ์‚ฌ์šฉ์ž ์ธํ„ฐํŽ˜์ด์Šค ์š”์†Œ
  • ViewModel : View์™€ Model ์‚ฌ์ด์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ค‘๊ณ„ํ•˜๊ณ , ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ์„ ํ†ตํ•ด View์— ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌ

MVC์™€ MVVM์˜ ์ฐจ์ด์ 

  1. ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์ฒ˜๋ฆฌ:
    • MVC: ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ Controller๊ฐ€ ์ง์ ‘ ์ฒ˜๋ฆฌ
    • MVVM: ์‚ฌ์šฉ์ž ์ž…๋ ฅ์€ ViewModel์ด ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
  2. ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ:
    • MVC : ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ์ด ์ž๋™ X, Controller๋ฅผ ํ†ตํ•ด ์ˆ˜๋™์œผ๋กœ ์ฒ˜๋ฆฌ
    • MVVM : ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ์ด ์ž๋™, View์™€ ViewModel ๊ฐ„์˜ ๋ฐ์ดํ„ฐ ๋™๊ธฐํ™”๊ฐ€ ํ”„๋ ˆ์ž„์›Œํฌ์— ์˜ํ•ด ์ž๋™์œผ๋กœ ์ฒ˜๋ฆฌ

MVC
MVVM

์˜ˆ์‹œ ์ฝ”๋“œ

# Model
class Song:
    def __init__(self, title, artist):
        self.title = title
        self.artist = artist

# ViewModel
class SongViewModel:
    def __init__(self, song: Song):
        self._song = song

    @property
    def display_title(self):
        return f"{self._song.title} by {self._song.artist}"

# View
class SongView:
    def __init__(self, viewmodel: SongViewModel):
        self.viewmodel = viewmodel

    def show(self):
        print(self.viewmodel.display_title)

# ์‚ฌ์šฉ ์˜ˆ์‹œ
song = Song("How sweet", "๋‰ด์ง„์Šค")
song_vm = SongViewModel(song)
view = SongView(song_vm)
view.show()
728x90