observer.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Поведенческий шаблон проектирования ("Наблюдатель")
  2. # Позволяет одним объектам следить и реагировать на события, происходящие в других объектах.
  3. import abc
  4. import typing
  5. class IObserver(metaclass=abc.ABCMeta):
  6. @abc.abstractmethod
  7. def update(self, p: int):
  8. pass
  9. class IObservable(metaclass=abc.ABCMeta):
  10. @abc.abstractmethod
  11. def add_observer(self, o: IObserver):
  12. pass
  13. @abc.abstractmethod
  14. def remove_observer(self, o: IObserver):
  15. pass
  16. @abc.abstractmethod
  17. def notify(self):
  18. pass
  19. class Product(IObservable):
  20. def __init__(self, price: int):
  21. self.__price = price
  22. self.__observers: typing.List[IObserver] = []
  23. def change_price(self, price: int):
  24. self.__price = price
  25. self.notify()
  26. def add_observer(self, o: IObserver):
  27. self.__observers.append(o)
  28. def remove_observer(self, o: IObserver):
  29. self.__observers.remove(o)
  30. def notify(self):
  31. for o in self.__observers:
  32. o.update(self.__price)
  33. class Wholesale(IObserver):
  34. def __init__(self, obj: IObservable):
  35. self.__product = obj
  36. obj.add_observer(self)
  37. def update(self, p: int):
  38. if p < 300:
  39. print('Оптовик закупил товар по цене {}'.format(p))
  40. self.__product.remove_observer(self)
  41. class Buyer(IObserver):
  42. def __init__(self, obj: IObservable):
  43. self.__product = obj
  44. obj.add_observer(self)
  45. def update(self, p: int):
  46. if p < 350:
  47. print('Покупатель закупил товар по цене {}'.format(p))
  48. if __name__ == '__main__':
  49. product = Product(400)
  50. wholesale = Wholesale(product)
  51. buyer = Buyer(product)
  52. product.change_price(320)
  53. product.change_price(280)
  54. product.change_price(310)
  55. # Покупатель закупил товар по цене 320
  56. # Оптовик закупил товар по цене 280
  57. # Покупатель закупил товар по цене 310