0
0

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.

【Python】Observerパターン

Last updated at Posted at 2017-12-09
# !/usr/bin/env python
# -*- coding: utf-8 -*-

from abc import ABCMeta, abstractmethod

class Subject(metaclass=ABCMeta):
    @abstractmethod
    def attach(self, observer):
        pass

    @abstractmethod
    def detach(self, observer):
        pass

    @abstractmethod
    def notify(self):
        pass

class Observer(metaclass=ABCMeta):
    @abstractmethod
    def update(self, subject):
        pass

class Newspaper(Subject):
    def __init__(self, name):
        self.__name = name
        self.__observers = []
        self.__content = ""

    def attach(self, observer):
        self.__observers.append(observer)

    def detach(self, observer):
        if observer in self.__observers:
            self.__observers.remove(observer)

    def breakOutNews(self, content):
        self.__content = content
        self.notify()

    def getContent(self):
        return self.__content + '(' + self.__name + ')'

    def notify(self):
        for each in self.__observers:
            each.update(self)

class Reader(Observer):
    def __init__(self, name):
        self.__name = name

    def update(self, subject):
        print(self.__name, "is reading breakout news <b>" + subject.getContent() + "</b><br>")

if __name__ == "__main__":
    asahi = Newspaper("Asahi")

    sato = Reader("Sato")
    suzuki = Reader("Suzuki")
    tanaka = Reader("Tanaka")

    asahi.attach(sato)
    asahi.attach(suzuki)
    asahi.attach(tanaka)

    asahi.detach(tanaka)

    asahi.breakOutNews("Japan Break down!")
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?