PHpullh
학습 라이브러리/Python/리포지토리 패턴

PYTHON · 디자인패턴

리포지토리 패턴

리포지토리 패턴으로 데이터 접근 로직을 추상화하여 비즈니스 로직과 분리합니다.

디자인패턴고급repository리포지토리데이터 접근추상화

핵심 설명

리포지토리 패턴으로 데이터 접근 로직을 추상화하여 비즈니스 로직과 분리합니다.

Python code

from abc import ABC, abstractmethod
from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    email: str

class UserRepository(ABC):
    @abstractmethod
    def find_by_id(self, user_id: int) -> User | None: ...
    @abstractmethod
    def find_all(self) -> list[User]: ...
    @abstractmethod
    def save(self, user: User) -> User: ...
    @abstractmethod
    def delete(self, user_id: int) -> bool: ...

class InMemoryUserRepository(UserRepository):
    def __init__(self):
        self._store: dict[int, User] = {}
        self._next_id = 1

    def find_by_id(self, user_id: int) -> User | None:
        return self._store.get(user_id)

    def find_all(self) -> list[User]:
        return list(self._store.values())

    def save(self, user: User) -> User:
        if user.id == 0:
            user = User(self._next_id, user.name, user.email)
            self._next_id += 1
        self._store[user.id] = user
        return user

    def delete(self, user_id: int) -> bool:
        return self._store.pop(user_id, None) is not None

# 비즈니스 로직은 추상 인터페이스에만 의존
def register_user(repo: UserRepository, name: str, email: str):
    user = repo.save(User(0, name, email))
    print(f"등록: {user}")
    return user

repo = InMemoryUserRepository()
register_user(repo, "Alice", "alice@test.com")
register_user(repo, "Bob", "bob@test.com")
print(f"전체: {repo.find_all()}")

학습 팁

리포지토리 인터페이스를 ABC로 정의하면 테스트 시 InMemory 구현으로 쉽게 교체할 수 있습니다.

주의할 점

리포지토리에 비즈니스 로직을 넣지 마세요. 리포지토리는 순수한 데이터 접근만 담당합니다.

자주 묻는 질문

리포지토리 패턴란 무엇인가요?

리포지토리 패턴으로 데이터 접근 로직을 추상화하여 비즈니스 로직과 분리합니다.

리포지토리 패턴 학습 시 주의할 점은 무엇인가요?

리포지토리에 비즈니스 로직을 넣지 마세요. 리포지토리는 순수한 데이터 접근만 담당합니다.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.