Python设计模式之单例模式 -- 实现日志记录器单例

一、单例模式简介

概述:要求一个类有且仅有一个实例,并且提供了一个全局的访问点。

应用场景:日志插入、计时器、权限校验、回收站、网站计数器、线程池、数据库连接池等资源池。

 

 二、日志记录器的实现

一个对象的实例化过程是先执行类的__new__方法,如果我们没有写,默认会调用object的__new__方法,返回一个实例化对象,然后再调用__init__方法,对这个对象进行初始化,我们可以根据这个实现单例.

在一个类的__new__方法中先判断是不是存在实例,如果存在实例,就直接返回,如果不存在实例就创建.

# 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************")

控制台输出如下:

566521222648 logger2.log
566521222648 logger2.log

生成一个logger2.log文件,文件内容如下:

[INFO]log1************
[WARN]log1************
[INFO]log2************
[WARN]log2************

结果表明:日志信息内容记录在同一个文件中

 

参考资料

[Wessel Badenhorst]Practical Python Design Patterns:Pyrhonic Solution to Common Problems

https://blog.csdn.net/sxb0841901116/article/details/78506643

https://blog.csdn.net/Burgess_zheng/article/details/86762248#%C2%A0%20%C2%A0%C2%A0%20%C2%A0%20%C2%A05.%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%EF%BC%88Singleton%EF%BC%89

https://www.runoob.com/design-pattern/singleton-pattern.html

你可能感兴趣的:(Python学习之路)