banner
Jun 7, 2023
103 Views

Singleton Pattern

Written by
banner

Ensure a class only has one instance, and provide a global point of access to it.

Đảm bảo một class chỉ có một instance duy nhất và cung cấp một điểm truy cập toàn cục đến instance đó.

Ví dụ: bạn code app và muốn chỉ có 1 log instance duy nhất cho toàn ứng dụng

import sys
import logging


class Logger:
    __instance = None

    @staticmethod
    def getInstance():
        """ Static access method. """
        if Logger.__instance == None:
            Logger()
        return Logger.__instance

    def __init__(self):
        """ Virtually private constructor. """
        if Logger.__instance == None:
            Logger.__instance = logging.getLogger()
            Logger.__instance.setLevel(logging.INFO)
            formatter = logging.Formatter(
                fmt='[%(asctime)s] [%(filename)s:%(lineno)d] %(levelname)s - %(message)s',
                datefmt='%H:%M:%S',
            )
            # file_handler = logging.FileHandler(filename='out_of_stock.log', mode='a', )
            stdout_handler = logging.StreamHandler(stream=sys.stdout)
            stdout_handler.setFormatter(formatter)
            # file_handler.setFormatter(formatter)
            handlers = [stdout_handler]
            Logger.__instance.handlers = handlers

#test
s1 = Logger.getInstance()
print(s1)

#try to init other Logger in other files ?
s2 = Logger.getInstance()
print(s2)

#Will it be the same ?
print(s1 is s2)
"""
OUTPUT

<__main__.Logger object at 0x7fde4a653fa0>
<__main__.Logger object at 0x7fde4a653fa0>
True
"""
Article Tags:
Article Categories:
config
banner

Leave a Reply

Your email address will not be published. Required fields are marked *