PYTHON · 디자인패턴
데코레이터 패턴 활용
객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다. Python 데코레이터와는 다른 GoF 패턴입니다.
디자인패턴중급decorator pattern데코레이터 패턴GoF래퍼
핵심 설명
객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다. Python 데코레이터와는 다른 GoF 패턴입니다.
Python code
from abc import ABC, abstractmethod
class DataSource(ABC):
@abstractmethod
def write(self, data: str) -> None: ...
@abstractmethod
def read(self) -> str: ...
class FileDataSource(DataSource):
def __init__(self):
self._data = ""
def write(self, data: str):
self._data = data
def read(self) -> str:
return self._data
class DataSourceDecorator(DataSource):
def __init__(self, source: DataSource):
self._source = source
def write(self, data: str):
self._source.write(data)
def read(self) -> str:
return self._source.read()
class EncryptionDecorator(DataSourceDecorator):
def write(self, data: str):
encrypted = data[::-1] # 간단한 암호화 시뮬레이션
print(f" [암호화] {data[:20]}...")
super().write(encrypted)
def read(self) -> str:
return super().read()[::-1]
class CompressionDecorator(DataSourceDecorator):
def write(self, data: str):
compressed = data.replace(" ", " ")
print(f" [압축] {len(data)} → {len(compressed)} chars")
super().write(compressed)
def read(self) -> str:
return super().read()
# 데코레이터 조합
source = FileDataSource()
encrypted = EncryptionDecorator(source)
compressed = CompressionDecorator(encrypted)
compressed.write("Hello World Python Programming")
result = compressed.read()
print(f"읽기: {result}")학습 팁
GoF 데코레이터 패턴은 상속 대신 조합으로 기능을 확장합니다. Python 데코레이터(@)와 혼동하지 마세요.
주의할 점
너무 많은 데코레이터를 중첩하면 디버깅이 어렵습니다. 3-4개 이상이면 다른 패턴을 고려하세요.
자주 묻는 질문
데코레이터 패턴 활용란 무엇인가요?
객체에 동적으로 기능을 추가하는 데코레이터 패턴입니다. Python 데코레이터와는 다른 GoF 패턴입니다.
데코레이터 패턴 활용 학습 시 주의할 점은 무엇인가요?
너무 많은 데코레이터를 중첩하면 디버깅이 어렵습니다. 3-4개 이상이면 다른 패턴을 고려하세요.