일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Container
- docker
- Flask
- Laravel
- judge
- KAKAO
- Mac
- git
- Converting
- Paper
- Database
- pandas
- LLM
- Package
- enV
- list
- Linux
- Python
- GitLab
- DB
- PostgreSQL
- file
- TORCH
- AI
- CUDA
- evaluation
- format
- Windows
- pytorch
- numpy
Archives
- Today
- Total
Daily Develope
[Python] Pattern - Singleton (싱글톤) 본문
Singleton
ㅇ 사용 목적
- 하나의 클래스가 오직 하나의 인스턴스만을 가지도록하여, 해당 인스턴스를 전역에서 접근 가능하도록 제공
- 주로 Logging 이나 DB 접근에서 사용. (자주 호출되는 인스턴스가 필요한 경우 정의/사용)
ㅇ 장점
- 필요할 때 단일 인스턴스를 생성, 생성된 인스턴스는 메모리에 상주하며 다음 호출시 사용
ㅇ 주의
- 생성된 인스턴스는 메모리에 상주하고 있기 때문에 자원관리 필요
- 하나의 인스턴스 자원을 공유하므로 ripple effect 주의
ㅇ MariaDB 예제
더보기
- Singleton DB Class 정의
import mariadb
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwds):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwds)
return cls._instances[cls]
class MyDBManager(metaclass=MetaSingleton):
_connection = None
_cur = None
def connect(self):
try:
if not self._connection:
self._connection = mariadb.connect(
user='root',
password='mypasswd',
host='127.0.0.1',
port=3306,
database='mydb')
self._cur = self._connection.cursor()
return self._cur
except mariadb.Error as e:
print(f'[ERR] Connecting to MariaDB : {e}')
def createTable(self, table_name):
# implements...
pass
- Singleton 클래스 사용
from MyDBManager import MyDBManager
mdbm = MyDBManager()
dbcur = nbdm.connect()
dbcur.execute("SELECT * FROM mytable")
for data in dbcur:
print(data)
- 한 번 선언된 이후에는 타-클래스에서 바로 사용 가능
from MyDBManager import MyDBManager
db_inst = MyDBManager().createTable("myTable")
ㅇ 참조
- https://refactoring.guru/design-patterns/singleton
- https://python.astrotech.io/design-patterns/creational/singleton.html
'Develope > Python' 카테고리의 다른 글
[Python] config 환경설정 관리 및 사용 (0) | 2022.03.31 |
---|---|
[Python] PCM 음성파일 파형 출력 (with pyplot) (0) | 2022.02.15 |
[Python] PCM 파일 통합 및 WAV로 변환 (0) | 2022.02.15 |
[Python] 매칭 (문자열 / 리스트 / 정규식) (0) | 2022.01.15 |
[Python] 로그, 로깅 (logging) (0) | 2022.01.15 |