---
# System prepended metadata

title: singleton
tags: [實作相關]

---

singleton
===
示範如何寫入 `.cfg` 檔
```python=
import configparser
import os
import logging

class SysConnConfigUtil:
    _instance = None
    FILE_NAME = "sysConn.cfg"
    conf_directory = "conf"
    config_file_path = os.path.join('.', conf_directory + '/' + FILE_NAME).replace('\\', '/')

    config = configparser.ConfigParser()
    config.read(config_file_path)

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        pass

    def set_conn(self, conn):
        logging.info(f"Update 'conn' = {conn}")
        self.config['sysConn']['conn'] = str(conn)
        with open(self.config_file_path, 'w') as f:
            self.config.write(f)
        
    def get_conn(self):
        conn = self.config['sysConn'].getint('conn')
        return conn

```

## Ref.
[python 實現 singleton 模式](https://mark1002.github.io/2018/07/31/python-%E5%AF%A6%E7%8F%BE-singleton-%E6%A8%A1%E5%BC%8F/)

###### tags: `實作相關`