1. Introduction to Singleton Mode
Overview: Requires one and only one instance of a class, and provides a global access point.
Application scenarios: resource pools such as log insertion, timers, permission verification, recycle bins, website counters, thread pools, database connection pools, etc.
Second, the realization of the log recorder
The instantiation process of an object is to execute the class __new__方法
first.If we don't write it, the object __new__
method will be called by default , returning an instantiated object, and then calling __init__方法
to initialize this object.We can implement a singleton based on this.
__new__方法中
First judge whether there is an instance in a class , if there is an instance, it will return directly, if there is no instance, it will be created.
# coding=utf-8
class Singleton(object):
"""
单例类
"""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls) # python3
# cls._instance = super(Singleton, cls).__new__(cls,*args, **kwargs) # python2
return cls._instance
class Logger(Singleton):
"""
日志
"""
def __init__(self, file_name):
self.filename = file_name
def _write_log(self, level, msg):
with open(self.filename, "a") as log_file:
log_file.write("[{0}]{1}\n".format(level, msg))
def critical(self, msg):
self._write_log("CRITICAL", msg)
def error(self, msg):
self._write_log("ERROR", msg)
def warn(self, msg):
self._write_log("WARN", msg)
def info(self, msg):
self._write_log("INFO", msg)
def debug(self, msg):
self._write_log("DEBUG", msg)
if __name__ == '__main__':
log1 = Logger("logger1.log")
log2 = Logger("logger2.log")
print(id(log1), log1.filename)
print(id(log2), log2.filename)
log1.info("log1************")
log1.warn("log1************")
log2.info("log2************")
log2.warn("log2************")
The console output is as follows:
566521222648 logger2.log
566521222648 logger2.log
Generate a logger2.log file, the content of the file is as follows:
[INFO] log1 ************ [WARN]log1************ [INFO] log2 ************ [WARN]log2************
The results show that: the content of the log information is recorded in the same file
Reference
[Wessel Badenhorst]Practical Python Design Patterns:Pyrhonic Solution to Common Problems
https://blog.csdn.net/sxb0841901116/article/details/78506643
https://www.runoob.com/design-pattern/singleton-pattern.html