Advertisement
Guest User

Untitled

a guest
Nov 28th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. def singleton(cls):
  2. instances = {}
  3.  
  4. def get_instance():
  5. if cls not in instances:
  6. instances[cls] = cls()
  7. return instances[cls]
  8.  
  9. return get_instance
  10.  
  11.  
  12. @singleton
  13. class Package(object):
  14. def register(self, name, module):
  15. setattr(self, name, module)
  16.  
  17.  
  18. def inject(*modules):
  19. def wrapper(cls):
  20. for module in modules:
  21. setattr(cls, module, getattr(Package(), module))
  22. return cls
  23. return wrapper
  24.  
  25.  
  26. def register(name):
  27. def wrapper(cls):
  28. configurations = {
  29. 'database': (
  30. ('mysql', ),
  31. {'host': 'localhost', 'user': 'user', 'password': 'password'}
  32. )
  33. }
  34.  
  35. if name in configurations:
  36. args, kwargs = configurations[name]
  37. else:
  38. args, kwargs = [], {}
  39.  
  40. Package().register(name, cls(*args, **kwargs))
  41.  
  42. return cls
  43. return wrapper
  44.  
  45.  
  46. @register("database")
  47. class Database(object):
  48. def __init__(self, db_type, host=None, user=None, password=None):
  49. self.db_type = db_type
  50. self.host = host
  51.  
  52. def __str__(self):
  53. return self.db_type + " @ " + self.host
  54.  
  55.  
  56. @register("metric")
  57. @inject("database")
  58. class Metric:
  59. def test(self):
  60. print self.database
  61.  
  62. def __str__(self):
  63. return "metric instance"
  64.  
  65.  
  66. @inject("database", "metric")
  67. class Analyzer:
  68. def test(self):
  69. print self.database
  70. print self.metric
  71.  
  72.  
  73. #instance0 = Database()
  74.  
  75. instance1 = Metric()
  76. instance1.test()
  77.  
  78. instance2 = Analyzer()
  79. instance2.test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement