meta_3.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. '''
  2. Паттерн Singleton
  3. Паттерн гарантирует, что класс имеет только один экземпляр,
  4. предоставляет глобальную точку доступа к этому экзеемпляру.
  5. Этот экземпляр обычно предоставляет доступ к определенным
  6. ресурсам или слажбам, таким как база данных, файловая система
  7. или любая другая общая ресурсоемкая операция.
  8. '''
  9. class Singleton:
  10. _instance = None
  11. def __new__(cls):
  12. if not cls._instance:
  13. cls.instance = super(Singleton, cls).__new__(cls)
  14. return cls._instance
  15. def test_1():
  16. instance_1 = Singleton()
  17. instance_2 = Singleton()
  18. print(id(instance_1))
  19. print(id(instance_2))
  20. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  21. class AppSettings:
  22. __instance = None
  23. def __new__(cls):
  24. if not cls.__instance:
  25. cls.__instance = super(AppSettings, cls).__new__(cls)
  26. # Логика инициализации настроек (может быть сложной)
  27. cls.__instance.initialize_settings()
  28. return cls.__instance
  29. def initialize_settings(self):
  30. # Логика инициализации настроек
  31. self.app_name = 'MyApp 1.0'
  32. self.debug_mode = False
  33. self.log_level = 'INFO'
  34. @staticmethod
  35. def get_app():
  36. if not AppSettings.__instance:
  37. AppSettings.__new__(AppSettings)
  38. return AppSettings.__instance
  39. def test_2():
  40. app_settings_1 = AppSettings.get_app()
  41. app_settings_2 = AppSettings()
  42. print(app_settings_1 is app_settings_2) # Выдает True
  43. print(app_settings_1.app_name)
  44. print(app_settings_2.app_name)
  45. print(app_settings_1.debug_mode)
  46. print(app_settings_2.debug_mode)
  47. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  48. class Logger:
  49. __instance = None
  50. def __new__(cls):
  51. if not cls.__instance:
  52. cls.__instance = super(Logger, cls).__new__(cls)
  53. cls.log_level = 'INFO'
  54. return cls.__instance
  55. @staticmethod
  56. def set_level(level):
  57. if not Logger.__instance:
  58. raise ValueError('The instance has not created')
  59. Logger.log_level = level
  60. def new_method(self, level):
  61. return level
  62. @staticmethod
  63. def get_logger():
  64. if not Logger.__instance:
  65. Logger.__new__(Logger)
  66. return Logger.__instance
  67. def test_3():
  68. logger_1 = Logger.get_logger()
  69. print(logger_1.log_level) # Выведет "INFO"
  70. Logger.set_level("DEBUG")
  71. print(logger_1.log_level) # Выведет "DEBUG"
  72. logger_2 = Logger.get_logger()
  73. print(logger_2.log_level) # Выведет "DEBUG"
  74. print(logger_2 is logger_1)
  75. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  76. '''
  77. def singleton(func):
  78. def wrapper():
  79. original_result = func()
  80. modified_result = original_result + 1
  81. return modified_result
  82. return wrapper
  83. '''
  84. def singleton(cls):
  85. foo = None
  86. def wrapper():
  87. nonlocal foo
  88. if foo is None:
  89. foo = cls()
  90. return foo
  91. return wrapper
  92. @singleton
  93. class Logger:
  94. pass
  95. @singleton
  96. class AppConfig:
  97. pass
  98. @singleton
  99. class SMTPServerConfig:
  100. pass
  101. def test_4():
  102. log = Logger()
  103. app_conf = AppConfig()
  104. app_conf_2 = AppConfig()
  105. smtp_conf = SMTPServerConfig()
  106. assert log is Logger()
  107. assert app_conf is app_conf_2
  108. assert smtp_conf is SMTPServerConfig()
  109. assert log is not app_conf
  110. assert log is not smtp_conf
  111. assert app_conf is not smtp_conf
  112. print('Good')
  113. def main():
  114. # test_1()
  115. # test_2()
  116. # test_3()
  117. test_4()
  118. if __name__ == '__main__':
  119. main()