Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def singleton(cls):
- instances = {}
- def get_instance():
- if cls not in instances:
- instances[cls] = cls()
- return instances[cls]
- return get_instance
- @singleton
- class Package(object):
- def register(self, name, module):
- setattr(self, name, module)
- def inject(*modules):
- def wrapper(cls):
- for module in modules:
- setattr(cls, module, getattr(Package(), module))
- return cls
- return wrapper
- def register(name):
- def wrapper(cls):
- configurations = {
- 'database': (
- ('mysql', ),
- {'host': 'localhost', 'user': 'user', 'password': 'password'}
- )
- }
- if name in configurations:
- args, kwargs = configurations[name]
- else:
- args, kwargs = [], {}
- Package().register(name, cls(*args, **kwargs))
- return cls
- return wrapper
- @register("database")
- class Database(object):
- def __init__(self, db_type, host=None, user=None, password=None):
- self.db_type = db_type
- self.host = host
- def __str__(self):
- return self.db_type + " @ " + self.host
- @register("metric")
- @inject("database")
- class Metric:
- def test(self):
- print self.database
- def __str__(self):
- return "metric instance"
- @inject("database", "metric")
- class Analyzer:
- def test(self):
- print self.database
- print self.metric
- #instance0 = Database()
- instance1 = Metric()
- instance1.test()
- instance2 = Analyzer()
- instance2.test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement