KOTLIN · 디자인패턴
스펙 패턴 (Specification)
비즈니스 규칙을 조합 가능한 객체로 캡슐화합니다. AND, OR, NOT 연산으로 복합 조건을 구성합니다.
디자인패턴고급specificationbusiness-rulecomposabledomain-driven
핵심 설명
비즈니스 규칙을 조합 가능한 객체로 캡슐화합니다. AND, OR, NOT 연산으로 복합 조건을 구성합니다.
Kotlin code
fun interface Spec<T> {
fun isSatisfiedBy(candidate: T): Boolean
infix fun and(other: Spec<T>): Spec<T> =
Spec { isSatisfiedBy(it) && other.isSatisfiedBy(it) }
infix fun or(other: Spec<T>): Spec<T> =
Spec { isSatisfiedBy(it) || other.isSatisfiedBy(it) }
operator fun not(): Spec<T> = Spec { !isSatisfiedBy(it) }
}
data class Product(val name: String, val price: Int, val category: String, val inStock: Boolean)
// 스펙 정의
val inStock = Spec<Product> { it.inStock }
val affordable = Spec<Product> { it.price < 50000 }
val isElectronics = Spec<Product> { it.category == "전자기기" }
fun priceRange(min: Int, max: Int) = Spec<Product> { it.price in min..max }
fun main() {
val products = listOf(
Product("마우스", 30000, "전자기기", true),
Product("키보드", 80000, "전자기기", true),
Product("노트", 3000, "문구", true),
Product("모니터", 350000, "전자기기", false),
)
// 스펙 조합
val buyable = inStock and affordable and isElectronics
val premium = isElectronics and priceRange(100000, 500000)
println("구매 가능: ${products.filter { buyable.isSatisfiedBy(it) }.map { it.name }}")
println("프리미엄: ${products.filter { premium.isSatisfiedBy(it) }.map { it.name }}")
println("재고없음: ${products.filter { (!inStock).isSatisfiedBy(it) }.map { it.name }}")
}학습 팁
스펙 패턴은 복잡한 쿼리 조건, 할인 규칙, 접근 제어 등 비즈니스 규칙이 자주 변하는 도메인에 유용합니다.
주의할 점
스펙을 너무 세분화하면 조합이 복잡해집니다. 자주 함께 사용하는 스펙은 하나로 합쳐서 명명하세요.
자주 묻는 질문
스펙 패턴 (Specification)란 무엇인가요?
비즈니스 규칙을 조합 가능한 객체로 캡슐화합니다. AND, OR, NOT 연산으로 복합 조건을 구성합니다.
스펙 패턴 (Specification) 학습 시 주의할 점은 무엇인가요?
스펙을 너무 세분화하면 조합이 복잡해집니다. 자주 함께 사용하는 스펙은 하나로 합쳐서 명명하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.