๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ

[Kotlin] Delegation

kotlinlang.org/docs/delegation.html#overriding-a-member-of-an-interface-implemented-by-delegation

 

Delegation - Help | Kotlin

 

kotlinlang.org

Delegation pattern ์€ ์ƒ์†์„ ๊ตฌํ˜„ํ•˜๋Š”๋ฐ์— ๋Œ€์ฒดํ•˜๊ธฐ ์ข‹๊ณ , Kotlin์€ ๋ณด์ผ๋Ÿฌ์ฝ”๋“œ ์—†์ด ์‚ฌ์šฉํ•˜๋„๋ก ์ง€์›ํ•œ๋‹ค.

-> Delegation pattern ํ™•์ธ

 

Derived ํด๋ž˜์Šค๋Š” ์ง€์ •ํ•œ ๊ฐ์ฒด(์—ฌ๊ธฐ์„œ๋Š” BaseImpl)๋กœ ๋ชจ๋“  public ๋ฉค๋ฒ„๋“ค์„ ์œ„์ž„ํ•ด์„œ Base ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(b: Base) : Base by b

fun main() {
    val b = BaseImpl(10)
    Derived(b).print()
}

๊ฒฐ๊ณผ

10

Derived์˜ ์ƒ์œ„ํƒ€์ž… ๋ชฉ๋ก(supertype list)์—์„œ by ์ ˆ์€ b๊ฐ€ Derived ๊ฐ์ฒด์— ๋‚ด๋ถ€์ ์œผ๋กœ ์ €์žฅ๋  ๊ฒƒ์ด๊ณ  ์ปดํŒŒ์ผ๋Ÿฌ๋Š” b๋กœ ์ „๋‹ฌ๋˜๋Š” Base์˜ ๋ชจ๋“  ๋ฉ”์†Œ๋“œ๋“ค์„ ์ƒ์„ฑํ•  ๊ฒƒ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. 

 

delegation(์œ„์ž„)์— ์˜ํ•ด ๊ตฌํ˜„๋œ ์ธํ„ฐํŽ˜์ด์Šค์˜ ๋ฉค๋ฒ„๋ฅผ overriding(์žฌ์ •์˜)ํ•˜๊ธฐ

override๋Š” ์˜ˆ์ƒ๋Œ€๋กœ ๋™์ž‘ํ•œ๋‹ค. ์ปดํŒŒ์ผ๋Ÿฌ๋Š” delegate ๊ฐ์ฒด(์œ„์ž„ ๊ฐ์ฒด, ์˜ˆ์‹œ์—์„œ๋Š” BaseImpl) ๋Œ€์‹ ์— override ๊ตฌํ˜„์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค. 

Derived์— override fun printMessage() { print("abe") } ๋ฅผ ์ถ”๊ฐ€ํ•˜๋ฉด, ํ”„๋กœ๊ทธ๋žจ์€ printMessage๊ฐ€ ํ˜ธ์ถœ๋  ๋•Œ 10 ๋Œ€์‹ ์— abc๋ฅผ printํ•  ๊ฒƒ์ด๋‹ค.

 

interface Base {
    fun printMessage()
    fun printMessageLine()
}

class BaseImpl(val x: Int) : Base {
    override fun printMessage() { print(x) }
    override fun printMessageLine() { println(x) }
}

class Derived(b: Base) : Base by b {
    override fun printMessage() { print("abc") }
}

fun main() {
    val b = BaseImpl(10)
    Derived(b).printMessage()
    Derived(b).printMessageLine()
}

๊ฒฐ๊ณผ

abc10

๊ทธ๋ ‡์ง€๋งŒ ์ด ๋ฐฉ์‹์œผ๋กœ ์žฌ์ •์˜๋œ(overriden) ๋ฉค๋ฒ„๋“ค์€ ์œ„์ž„ ๊ฐ์ฒด(์˜ˆ์ œ์—์„œ๋Š” BaseImpl)๊ฐ€  ์œ„์ž„ ๊ฐ์ฒด์—์„œ ์žฌ์ •์˜๋œ ๊ฐ’์œผ๋กœ ํ˜ธ์ถœ๋˜์ง€ ์•Š๊ณ , ์ธํ„ฐํŽ˜์ด์Šค ๋ฉค๋ฒ„๋“ค์˜ ๊ตฌํ˜„ ๊ฐ’์œผ๋กœ ์ ‘๊ทผํ•˜๊ฒŒ ๋œ๋‹ค.

interface Base {
    val message: String
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override val message = "BaseImpl: x = $x"
    override fun print() { println(message) }
}

class Derived(b: Base) : Base by b {
    // This property is not accessed from b's implementation of `print`
    // ์ด ํ”„๋กœํ”„ํ‹ฐ๋Š” b์—์„œ ๊ตฌํ˜„๋œ 'print'์—์„œ๋Š” ์ ‘๊ทผ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.
    override val message = "Message of Derived"
}

fun main() {
    val b = BaseImpl(10)
    val derived = Derived(b)
    derived.print()
    println(derived.message)
}

๊ฒฐ๊ณผ

BaseImpl: x = 10
Message of Derived

Delegation์€ ์ƒ์†์˜ ๋Œ€์•ˆ์šฉ

์ƒ์†ํ•  ์ˆ˜ ์—†๋Š” ํด๋ž˜์Šค์˜ ๊ธฐ๋Šฅ ์ถ”๊ฐ€ ๋ฐ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ