memento.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Поведенческий шаблон проектирования ("Снимок")
  2. # Позволяет сохранять и восстанавливать прошлые состояния объектов, не раскрывая подробностей их реализации. Не нарушает инкапсуляцию. Тратит много памяти
  3. import abc
  4. import typing
  5. class IMemento(metaclass=abc.ABCMeta):
  6. @abc.abstractmethod
  7. def get_dollars(self) -> int:
  8. pass
  9. @abc.abstractmethod
  10. def get_euro(self) -> int:
  11. pass
  12. class ExchangeMemento(IMemento):
  13. def __init__(self, d: int, e: int):
  14. self.__dollars = d
  15. self.__euro = e
  16. def get_dollars(self) -> int:
  17. return self.__dollars
  18. def get_euro(self) -> int:
  19. return self.__euro
  20. class Exchange:
  21. def __init__(self, d: int, e: int):
  22. self.__dollars = d
  23. self.__euro = e
  24. def get_dollars(self):
  25. print('Долларов: {}'.format(self.__dollars))
  26. def get_euro(self):
  27. print('Евро {}'.format(self.__euro))
  28. def sell(self):
  29. if self.__dollars > 0:
  30. self.__dollars -= 1
  31. def buy(self):
  32. self.__euro += 1
  33. def save(self) -> ExchangeMemento:
  34. return ExchangeMemento(self.__dollars, self.__euro)
  35. def restore(self, exchange_memento: IMemento):
  36. self.__dollars = exchange_memento.get_dollars()
  37. self.__euro = exchange_memento.get_euro()
  38. class Memory:
  39. def __init__(self, exchange: Exchange):
  40. self.__exchange = exchange
  41. self.__history: typing.Deque[IMemento] = []
  42. def backup(self):
  43. self.__history.append(self.__exchange.save())
  44. def undo(self):
  45. if len(self.__history) == 0:
  46. return
  47. else:
  48. self.__exchange.restore(
  49. self.__history.pop()
  50. )
  51. if __name__ == "__main__":
  52. exchange = Exchange(d=10, e=10)
  53. memory = Memory(exchange)
  54. exchange.get_dollars()
  55. exchange.get_euro()
  56. print('----- Продажа доллара, покупка евро -----')
  57. exchange.sell()
  58. exchange.buy()
  59. exchange.get_dollars()
  60. exchange.get_euro()
  61. print('----- Сохраним состояние -----')
  62. memory.backup()
  63. print('----- Продажа доллара, покупка евро -----')
  64. exchange.sell()
  65. exchange.buy()
  66. exchange.get_dollars()
  67. exchange.get_euro()
  68. print('----- Востановим состояние из памяти -----')
  69. memory.undo()
  70. exchange.get_dollars()
  71. exchange.get_euro()
  72. # Долларов: 10
  73. # Евро 10
  74. # ----- Продажа доллара, покупка евро -----
  75. # Долларов: 9
  76. # Евро 11
  77. # ----- Сохраним состояние -----
  78. # ----- Продажа доллара, покупка евро -----
  79. # Долларов: 8
  80. # Евро 12
  81. # ----- Востановим состояние из памяти -----
  82. # Долларов: 9
  83. # Евро 11