Singleton
Singleton
A GoF design pattern that ensures a class has only one instance. Offers various implementations such as Lazy, Eager, and Double-checked locking.
Singleton
A GoF design pattern that ensures a class has only one instance. Offers various implementations such as Lazy, Eager, and Double-checked locking.
The Singleton is a creational design pattern that guarantees that only one instance of a class exists across the entire application. It is used when a single, globally accessible object is needed. For example, it suits cases where the same instance must be shared in many places, such as a database connection pool, a logging system, or a configuration manager. A singleton is implemented by declaring the constructor private and accessing the sole instance through a static method.
The Singleton is one of the 23 design patterns published by the "Gang of Four (GoF)" in 1994 and belongs to the creational patterns. It is the most widely known and most used of the GoF patterns, but also the most controversial. It can violate the Single Responsibility Principle (SRP) and the Open-Closed Principle (OCP) of SOLID, the basic principles of object-oriented design, and it is criticized for creating global state that increases coupling in the code.
Singleton implementations fall into three broad types. Eager Initialization creates the instance when the class is loaded, so it is thread-safe, but it occupies memory even if unused. Lazy Initialization creates the instance on the first request, saving resources, but synchronization problems can arise in multithreaded environments. Double-Checked Locking secures both performance and thread safety, but it is complex to implement and requires additional handling such as the volatile keyword depending on the language.
In practice, singletons are still used for logging, caches, configuration management, and thread pools, but many developers regard them as an "antipattern." Singletons make unit testing difficult, hide dependencies, and can cause unpredictable behavior due to global state. In modern software development, managing object lifecycles through a Dependency Injection container is recommended instead of singletons. DI frameworks such as Spring and Guice support singleton scope while preserving testability.
Creates the instance when the class is loaded. Simple and thread-safe.
Creates the instance on first request. Resource-efficient but needs synchronization.
Secures both performance and thread safety. The volatile keyword is essential.
Lazy loading via an inner static class. Most recommended in Java.
# Python 싱글톤 구현 예제
from threading import Lock
from typing import Optional
# 1. 데코레이터를 활용한 싱글톤 (가장 Pythonic)
def singleton(cls):
"""싱글톤 데코레이터"""
instances = {}
lock = Lock()
def get_instance(*args, **kwargs):
if cls not in instances:
with lock: # 스레드 안전
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class DatabaseConnection:
"""데코레이터 방식 싱글톤"""
def __init__(self, host: str = "localhost"):
self.host = host
self.connected = False
print(f"DB 연결 생성: {host}")
def connect(self):
self.connected = True
print("DB 연결됨")
# 2. 메타클래스를 활용한 싱글톤 (고급)
class SingletonMeta(type):
"""싱글톤 메타클래스"""
_instances = {}
_lock = Lock()
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Logger(metaclass=SingletonMeta):
"""메타클래스 방식 싱글톤"""
def __init__(self):
self.logs = []
print("Logger 인스턴스 생성")
def log(self, message: str):
self.logs.append(message)
print(f"[LOG] {message}")
# 3. __new__를 활용한 싱글톤 (클래식)
class ConfigManager:
"""__new__ 오버라이드 방식"""
_instance: Optional['ConfigManager'] = None
_lock = Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if self._initialized:
return
self._initialized = True
self.config = {}
print("ConfigManager 초기화")
def set(self, key: str, value):
self.config[key] = value
def get(self, key: str, default=None):
return self.config.get(key, default)
# 4. 모듈 레벨 싱글톤 (가장 간단, Python 권장)
# config.py 파일로 분리하면 자동으로 싱글톤
class _AppConfig:
def __init__(self):
self.debug = False
self.version = "1.0.0"
app_config = _AppConfig() # 모듈 로드 시 한 번만 생성
# 사용 예제
if __name__ == "__main__":
# 데코레이터 싱글톤 테스트
db1 = DatabaseConnection("mysql://prod")
db2 = DatabaseConnection("mysql://dev") # 무시됨
print(f"같은 인스턴스? {db1 is db2}") # True
print(f"호스트: {db1.host}") # mysql://prod
# 메타클래스 싱글톤 테스트
logger1 = Logger()
logger2 = Logger() # 기존 인스턴스 반환
logger1.log("첫 번째 로그")
print(f"같은 인스턴스? {logger1 is logger2}") # True
# __new__ 싱글톤 테스트
config1 = ConfigManager()
config1.set("api_key", "secret123")
config2 = ConfigManager()
print(f"API Key: {config2.get('api_key')}") # secret123
"When implementing a singleton, you have to consider multithreaded environments. The simplest, the Eager approach, creates the instance at class loading, so it is thread-safe, but it occupies memory even if unused. The Lazy approach creates it when needed, but without synchronization more than one instance can appear. That is why Double-Checked Locking is used, and in Java the volatile keyword is essential. Personally, for Java I recommend the Bill Pugh approach or an Enum. Using an inner static class gives you both lazy loading and thread safety, and an Enum also defends against serialization and reflection attacks."
"Does this UserService really need to be a singleton? With the current structure, unit testing is almost impossible. Because it calls getInstance() directly, Mocks can't be injected, and global state is shared between tests, so results can vary depending on test order. It also depends directly on the DatabaseConnection singleton, which creates a hidden dependency. How about introducing dependency injection, receiving it through the constructor, and letting the DI container manage the object lifecycle? Like Spring's @Scope('singleton'). Then it behaves as a singleton in production while still allowing Mocks to be injected in tests."
"Let's use a singleton only where there truly must be exactly one globally, such as logging or configuration management, and otherwise use the DI container's singleton scope. Implementing singletons directly makes test isolation hard and debugging difficult when circular dependencies arise. In a microservice environment like our project in particular, it has to be fine for multiple instances to be running, and the singleton assumption can break. For database connection pools, use a proven library like HikariCP, and externalizing caches to Redis is better for scalability."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Singletons make unit testing very difficult. If you call getInstance() directly, it cannot be replaced with a Mock object, and state is shared between tests, breaking test isolation. "Flaky Tests" whose results depend on test order can occur. Use dependency injection and interfaces so that Mocks can be injected during testing.
With a singleton, a class's dependencies are not visible in its constructor or method signatures. Because getInstance() is called inside the code, it is hard to tell from outside what dependencies exist. This increases coupling and makes refactoring and maintenance difficult. Use constructor injection so that dependencies are explicit.
A singleton inherently creates global state. It can be accessed and modified from anywhere in the application, causing unpredictable behavior and bugs. Race conditions can occur in multithreaded environments, and in microservice or cluster environments multiple instances can exist, so the singleton assumption can break. Minimize state or separate it into external storage (such as Redis).