KOTLIN · 객체지향
팩토리 패턴 (Factory Pattern)
companion object의 팩토리 메서드로 객체 생성 로직을 캡슐화합니다. 인터페이스 기반 팩토리도 구현 가능합니다.
객체지향중급factory-patterncompanion-objectsealed-classcreation
핵심 설명
companion object의 팩토리 메서드로 객체 생성 로직을 캡슐화합니다. 인터페이스 기반 팩토리도 구현 가능합니다.
Kotlin code
sealed class Notification(val message: String) {
class Email(message: String, val to: String) : Notification(message)
class Sms(message: String, val phone: String) : Notification(message)
class Push(message: String, val token: String) : Notification(message)
companion object {
fun create(type: String, message: String, target: String): Notification =
when (type.lowercase()) {
"email" -> Email(message, target)
"sms" -> Sms(message, target)
"push" -> Push(message, target)
else -> throw IllegalArgumentException("알 수 없는 타입: $type")
}
}
fun send() = when (this) {
is Email -> println("이메일 → $to: $message")
is Sms -> println("SMS → $phone: $message")
is Push -> println("푸시 → $token: $message")
}
}
fun main() {
val noti = Notification.create("email", "환영합니다!", "user@test.com")
noti.send()
val sms = Notification.create("sms", "인증번호: 1234", "010-1234-5678")
sms.send()
}학습 팁
companion object 팩토리는 생성자와 달리 서브타입을 반환하거나 캐싱을 적용할 수 있어 유연합니다.
주의할 점
팩토리에 새 타입을 추가할 때 when 분기를 잊으면 else로 빠져 런타임 오류가 됩니다. sealed class를 활용하면 컴파일 타임에 잡을 수 있습니다.
자주 묻는 질문
팩토리 패턴 (Factory Pattern)란 무엇인가요?
companion object 의 팩토리 메서드로 객체 생성 로직을 캡슐화합니다. 인터페이스 기반 팩토리도 구현 가능합니다.
팩토리 패턴 (Factory Pattern) 학습 시 주의할 점은 무엇인가요?
팩토리에 새 타입을 추가할 때 when 분기를 잊으면 else 로 빠져 런타임 오류가 됩니다. sealed class를 활용하면 컴파일 타임에 잡을 수 있습니다.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.