utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from abc import ABCMeta
  2. from abc import abstractmethod
  3. import logging
  4. import threading
  5. logger = logging.getLogger(__name__)
  6. class Singleton(object):
  7. _instance_lock = threading.Lock()
  8. _init_flag = False
  9. def __new__(cls, *args, **kw):
  10. with Singleton._instance_lock:
  11. if not hasattr(cls, '_instance'):
  12. orig = super(Singleton, cls)
  13. cls._instance = orig.__new__(cls, *args, **kw)
  14. return cls._instance
  15. @classmethod
  16. def clear_instance(cls):
  17. cls._init_flag = False
  18. if hasattr(cls, '_instance'):
  19. del cls._instance
  20. def __init__(self) -> None:
  21. if Singleton._init_flag:
  22. return
  23. Singleton._init_flag = True
  24. class Observable(object):
  25. def __init__(self) -> None:
  26. self._observers = []
  27. def add_observer(self, observer):
  28. if observer not in self._observers:
  29. self._observers.append(observer)
  30. else:
  31. logger.error('Add observer %s failed !', observer)
  32. def remove_observer(self, observer):
  33. try:
  34. self._observers.remove(observer)
  35. except ValueError:
  36. logger.error('Failed to remove: %s', observer)
  37. @abstractmethod
  38. def notify_observers(self):
  39. return
  40. class Observer(metaclass=ABCMeta): # Observer
  41. @abstractmethod
  42. def update(self):
  43. pass