【Python】Observerパターン


#!/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!")