디자인 패턴(Design Pattern)은 소프트웨어 설계에서 반복적으로 나타나는 문제의 검증된 해결책이다. 1994년 GoF(Gang of Four)가 23가지 패턴을 정리했으며, 생성·구조·행동 패턴으로 분류된다.
패턴 분류
생성 패턴 (Creational)
python
# Singleton — 인스턴스를 하나만 생성
class Database:
_instance = None
@classmethod
def get_instance(cls):
if not cls._instance:
cls._instance = cls()
return cls._instance
# Factory Method — 객체 생성을 서브클래스에 위임
class AnimalFactory:
@staticmethod
def create(animal_type):
if animal_type == "dog": return Dog()
if animal_type == "cat": return Cat()
구조 패턴 (Structural)
python
# Decorator — 객체에 동적으로 기능 추가
def logging_decorator(func):
def wrapper(*args):
print(f"호출: {func.__name__}")
result = func(*args)
print(f"완료: {func.__name__}")
return result
return wrapper
@logging_decorator
def save_user(user): ...
# Adapter — 호환되지 않는 인터페이스를 연결
class LegacyAPI:
def old_method(self): ...
class Adapter:
def new_method(self):
return LegacyAPI().old_method()
행동 패턴 (Behavioral)
python
# Observer — 상태 변화를 다른 객체에 알림
class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, *args):
for cb in self._listeners.get(event, []):
cb(*args)
관련 개념
- •객체지향 프로그래밍 — 디자인 패턴의 기반
- •SOLID 원칙 — 디자인 패턴의 이론적 배경
참고문헌
- •Gamma et al. (1994). Design Patterns: Elements of Reusable Object-Oriented Software (GoF)