【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!")
Author And Source
この問題について(【Python】Observerパターン), 我々は、より多くの情報をここで見つけました https://qiita.com/sugar020855/items/cc027fc33475905d0805著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .