Python

CEO - CEO CEO CEO "CEO "


Python

Python

# singleton_module.py
class DatabaseConnection:
    def __init__(self):
        self.connection_string = "database://localhost:5432/mydb"
        print("")
   
    def query(self, sql):
        return f": {sql}"

#
db_instance = DatabaseConnection()

#
# from singleton_module import db_instance
# result = db_instance.query("SELECT * FROM users")

__new__

__new__

class Singleton:
    _instance = None
   
    def __new__(cls, *args, **kwargs):
        #
        if not cls._instance:
            cls._instance = super().__new__(cls)
            print("")
        else:
            print("")
        return cls._instance
   
    def __init__(self, name):
        # __init__
        self.name = name
        print(f": {name}")

#
print("=== ===")
s1 = Singleton("")
s2 = Singleton("")

print(f"s1 ID: {id(s1)}")
print(f"s2 ID: {id(s2)}")
print(f"s1 s2 {s1 is s2}")
print(f"s1 : {s1.name}")
print(f"s2 : {s2.name}")  # ""

===  ===

: 

: 
s1  ID: 140245678945600
s2  ID: 140245678945600
s1  s2  True
s1 : 
s2 : 

def singleton(cls):
    """"""
    instances = {}
   
    def get_instance(*args, **kwargs):
        #
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
            print(f" {cls.__name__} ")
        else:
            print(f" {cls.__name__} ")
        return instances[cls]
   
    return get_instance

@singleton
class ConfigurationManager:
    def __init__(self):
        self.settings = {}
        self.load_default_settings()
   
    def load_default_settings(self):
        self.settings = {
            "app_name": "",
            "version": "1.0.0",
            "debug_mode": True
        }
   
    def get_setting(self, key):
        return self.settings.get(key)
   
    def set_setting(self, key, value):
        self.settings[key] = value

#
print("\n=== ===")
config1 = ConfigurationManager()
config2 = ConfigurationManager()

config1.set_setting("theme", "dark")
print(f"config1 : {config1.get_setting('theme')}")
print(f"config2 : {config2.get_setting('theme')}")  #

class SingletonMeta(type):
    """"""
    _instances = {}
   
    def __call__(cls, *args, **kwargs):
        #
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
            print(f" {cls.__name__} ")
        else:
            print(f" {cls.__name__} ")
        return cls._instances[cls]

class Logger(metaclass=SingletonMeta):
    def __init__(self, log_file="app.log"):
        self.log_file = log_file
        self.logs = []
        print(f": {log_file}")
   
    def log(self, message):
        log_entry = f"[{self.get_timestamp()}] {message}"
        self.logs.append(log_entry)
        print(f": {log_entry}")
        return log_entry
   
    def get_timestamp(self):
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
   
    def get_logs(self):
        return self.logs.copy()

#
print("\n=== ===")
logger1 = Logger("application.log")
logger2 = Logger("different.log")  #

logger1.log("")
logger2.log("")

print(f"logger1 : {len(logger1.get_logs())}")
print(f"logger2 : {len(logger2.get_logs())}")
print(f" {logger1 is logger2}")

class AppConfig:
    _instance = None
   
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
   
    def __init__(self):
        #
        if not self._initialized:
            self.config_data = {}
            self.load_config()
            self._initialized = True
   
    def load_config(self):
        """"""
        self.config_data = {
            "database": {
                "host": "localhost",
                "port": 5432,
                "name": "myapp_db"
            },
            "server": {
                "host": "0.0.0.0",
                "port": 8000
            },
            "features": {
                "cache_enabled": True,
                "debug_mode": False
            }
        }
        print("")
   
    def get(self, key_path, default=None):
        """ 'database.host'"""
        keys = key_path.split('.')
        value = self.config_data
       
        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            return default
   
    def set(self, key_path, value):
        """"""
        keys = key_path.split('.')
        config = self.config_data
       
        #
        for key in keys[:-1]:
            if key not in config:
                config[key] = {}
            config = config[key]
       
        #
        config[keys[-1]] = value
        print(f": {key_path} = {value}")

#
def demonstrate_config_usage():
    print("\n=== ===")
   
    #
    config1 = AppConfig()
    config2 = AppConfig()
   
    print(f" {config1 is config2}")
   
    #
    db_host = config1.get("database.host")
    server_port = config1.get("server.port")
    print(f": {db_host}")
    print(f": {server_port}")
   
    #
    config2.set("database.host", "192.168.1.100")
    config2.set("features.debug_mode", True)
   
    #
    print(f"config1 : {config1.get('database.host')}")
    print(f"config1 : {config1.get('features.debug_mode')}")

#
demonstrate_config_usage()

class ThreadSafeSingleton:
    """"""
    _instance = None
    _lock = threading.Lock()
   
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                #
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    print("")
        return cls._instance
   
    def __init__(self):
        #
        if not hasattr(self, '_initialized'):
            self.data = {}
            self._initialized = True

    • JSON


Python __new__