Singleton Pattern
Sometimes we need one global object and use it in our application. Creating multiple instances for this object may create errors. especially errors about atomicity, integrity. So on those cases, we use Singleton pattern. We create the object once, initialize it than use it.
Wikipedia: In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
Example:
Let's assume we load our application configuration from Settings class. This class reads configuration from file. So when we create settings instance we should read configuration once and set variables once, return the instance. If we call settings instance again it should return variables without reading the configuration file.
settings.py
DOMAIN = "http://www.erdemozkol.com"
AUTHOR_NAME = "Erdem Ozkol"
DATE_FORMAT = "%A %d. %B %Y"
singleton.py
import settings
class Singleton(object):
def __init__(self, klass):
self.klass = klass # class which is being decorated
self.instance = None # instance of that class
def __call__(self, *args, **kwargs):
if self.instance is None:
# new instance is created and stored for future use
self.instance = self.klass(*args, **kwargs)
print "New instace created!"
print "Returning stored instance"
return self.instance
@Singleton
class Settings:
def __init__(self, module, *args, **kwargs):
for attr in dir(module):
# get all variable in settings.py and update the class attributes
setattr(self, attr, getattr(module, attr))
s1 = Settings(module=settings)
>>> "New instace created!"
>>> "Returning stored instance"
s2 = Settings(module=settings)
>>> "Returning stored instance"
s3 = Settings(module=settings)
>>> "Returning stored instance"
Bu implemention da ki class'lar yaptığı görevlere bir bakalım. Unit classından türetilen objeler observer class instance na register olduktan sonra objserver class bu unit'lere event gönderiyor. Yani tüm unit class'larini observer üzerinden dağıtık bir şekilde yönetebiliyoruz.
References: