LoginSignup
0
3

デザインパターン[MVVMの章]

Posted at
  1. 導入
    MVVMの概要
    MVVM(Model-View-ViewModel)は、ユーザーインターフェースの設計パターンの一つで、特にXAMLベースのアプリケーション(WPF、Xamarin、UWPなど)で人気があります。
    Model, View, ViewModelの三つのコンポーネントで構成されます。

MVVMの利点
MVVMの主な利点は、ビジネスロジックの分離、コードの再利用、テストの容易性です。

  1. Model(モデル)の役割
    データ管理とビジネスロジック
    モデルはアプリケーションのビジネスロジックやデータを管理します。

モデルの例と実装

from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    email: str

  1. View(ビュー)の役割
    ユーザーインターフェースの概要
    ビューは、ユーザーに表示されるUI部分を担当します。

ビューの例と実装

<StackPanel>
    <TextBlock Text="{Binding Name}" />
    <TextBlock Text="{Binding Email}" />
</StackPanel>
  1. ViewModel(ビューモデル)の役割
    状態管理とビューロジック
    ビューモデルはビューに表示するデータや状態を管理し、ビューロジックを担当します。

ビューモデルの例と実装

class UserViewModel:
    def __init__(self, user):
        self._user = user
        self._view = None 
        
    @property
    def name(self):
        return self._user.name
    
    @name.setter
    def name(self, value):
        if self._user.name != value:
            self._user.name = value
            self._update_view('name')
    
    @property
    def email(self):
        return self._user.email
    
    @email.setter
    def email(self, value):
        if self._user.email != value:
            self._user.email = value
            self._update_view('email')

    def attach_view(self, view):
        self._view = view
        self._update_view('name')
        self._update_view('email')

    def _update_view(self, prop_name):
        if self._view:
            if prop_name == 'name':
                self._view.name_label['text'] = "Name: " + self.name
            elif prop_name == 'email':
                self._view.email_label['text'] = "Email: " + self.email

  1. データバインディングの重要性
    データバインディングの概要
    MVVMにおいて、データバインディングはビューとビューモデルの間のデータ受け渡しを管理し、同期させます。

バインディングの例と実装

<StackPanel DataContext="{Binding UserViewModel}">
    <TextBox Text="{Binding Name, Mode=TwoWay}" />
    <TextBox Text="{Binding Email, Mode=TwoWay}" />
</StackPanel>
  1. まとめ
    MVVMパターンは、コードの整理とテストの容易性を提供し、ビジネスロジックとUIの分離を実現します。データバインディングの使用により、ビューとビューモデル間の同期が容易になります。
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3