#观察者模式之西游记师徒四人
#被观察者
class IMaster(object):
def __init__(self):
self._prentice_list = []
def name(self):
raise NotImplementedError
#收徒
def add_prentice(self, prentice):
if isinstance(prentice, type(IPrentice())):
print(self.name(),'has a new prentice:',prentice.name())
self._prentice_list.append(prentice)
prentice.set_master(self)
print()
else:
raise TypeError
#弃徒
def remove_prentice(self, prentice):
if isinstance(prentice, type(IPrentice())):
print('Remove Prentices :', prentice.name(), '\n')
self._prentice_list.remove(prentice)
else:
raise TypeError
#展示徒弟信息
def show_prentices(self):
if len(self._prentice_list) != 0:
print('Prentices Name List:')
for index, prentices in enumerate(self._prentice_list):
print(index+1, prentices.name())
else:
print('No prentices')
#给徒弟下命令
def order(self):
if len(self._prentice_list) != 0:
for index, prentices in enumerate(self._prentice_list):
prentices.listen(self._state)
else:
print('No prentices')
def set_state(self):
raise NotImplementedError
def get_state(self):
print("Now state is", self._state,'\n')
class TangSanzang(IMaster):
def __init__(self):
super().__init__()
self._state = "Rest"
def name(self):
return "TangSanzang"
#更改自己的状态并给徒弟下命令
def set_state(self):
while True:
state = input('Go(0) Or Rest(1) ?\n')
if state == "0" or state == "Go":
self._state = 'Go'
break
elif state == "1" or state == "Rest":
self._state = 'Rest'
break
self.order()
#观察者
class IPrentice(object):
def name(self):
raise NotImplementedError
#拜师
def set_master(self, master):
self._master = master
#听师傅说话
def listen(self, state):
raise NotImplementedError
class SunWukong(IPrentice):
def __init__(self):
self._state = "Rest"
def name(self):
return "SunWukong"
def listen(self, state):
if state == "Go":
self._state = "Vanquish demons and monsters"
print(self.name(), self._state)
if state == "Rest":
self._state = "Rest"
print(self.name(), self._state)
class ZhuBajie(IPrentice):
def __init__(self):
self._state = "Rest"
def name(self):
return "ZhuBajie"
def listen(self, state):
if state == "Go":
self._state = "Go"
print(self.name(), self._state)
if state == "Rest":
self._state = "Eat something"
print(self.name(), self._state)
class ShaWujing(IPrentice):
def __init__(self):
self._state = "Rest"
def name(self):
return "ShaWujing"
def listen(self, state):
if state == "Go":
self._state = "Go"
print(self.name(), self._state)
if state == "Rest":
self._state = "Rest"
print(self.name(), self._state)
def main():
Tang = TangSanzang()
sun = SunWukong()
zhu = ZhuBajie()
sha = ShaWujing()
Tang.add_prentice(sun)
Tang.add_prentice(zhu)
Tang.add_prentice(sha)
Tang.get_state()
Tang.set_state()
if __name__ == "__main__":
main()