5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Observer Patternを用いた簡素なMVCのpython実装例

Last updated at Posted at 2017-09-26

やること

  1. Viewはコンソールから入力されたテキストをControllerに渡す
  2. Controllerは入力されたテキストをModelに書き込む
  3. オブザーバーパータンでModelの変更を検知してViewを更新する

コード

class Model:
    def __init__(self):
        self.__observer = None
        self.__text = None

    def add_observer(self, observer):
        self.__observer = observer

    def notify_observer(self):
        self.__observer.update(self)

    @property
    def text(self):
        return self.__text

    @text.setter
    def text(self, text):
        self.__text = text
        self.notify_observer()


class View:
    def input(self):
        return input("Enter text: ")

    def update(self, model):
        print(model.text)


class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View()
        self.model.add_observer(self.view)

    def start(self):
        self.model.text = self.view.input()


if __name__ == '__main__':
    Controller().start()

参考資料

やはりお前らのMVCは間違っている
やはりおまえらの MVC は間違えている in バックボーンジェーエス
「MVCの勘違い」について、もう一度考えてみる
実践Python3

最後に

おかしな点,不明な点ありましたら遠慮なく指摘して下さい.

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?