Kotlin

위임자 Delegates (observable, vetoable )

kakaroo 2022. 5. 5. 10:24
반응형

디자인 패턴에서 Delegate Pattern이란 어떠한 기능을 자기 자신이 처리하지 않고 다른 객체에 일을 위임시켜 그 객체가 일을 처리하게끔 하는 것입니다.

코틀린의 Delegates를 활용하면 여러 가지 일을 간단하게 처리할 수가 있습니다.

 

 

article logo

 

 

observable

프로퍼티 값이 변경되는 순간을 감지하는 방법이 있습니다. 코틀린에서는 프로퍼티 값이 변경되는 순간, 개발자가 준비한 코드를 실행 할 수 있습니다.

 

Delegates.observable() 코드를 보면 initialValue와 onChange 함수를 인자로 사용됩니다.

public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit): 
	ReadWriteProperty<Any?, T> = 
    object : ObservableProperty<T>(initialValue) { 
    	override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue) 
    }
}

 

사용 예)

class User3 {
    var name: String by Delegates.observable("nonValue") { _, old, new -> println("old: $old, new: $new") }
}

 

 

vetoable

vetoable은 observable과 거의 유사하지만 반환 값이 boolean 입니다. 특정 조건을 만족할 경우에만 변수에 값이 설정됩니다.

public inline fun <T> vetoable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean): 
	ReadWriteProperty<Any?, T> = 
    object : ObservableProperty<T>(initialValue) { 
        override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue) 
    }
}

 

사용 예)

var max: Int by Delegates.vetoable(0) { property, oldValue, newValue ->
    if (newValue > oldValue) true else throw IllegalArgumentException("New value must be larger than old value.")
}

max = 10
println("max = $max")	//max = 10
max = 5					//runtime error ; Exception in thread "main" java.lang.IllegalArgumentException: New value must be larger than old value.
println("max = $max")

 

var odd: Int by Delegates.vetoable(0) { _, _, newValue -> newValue % 2 != 0 }
odd = 11
println("odd = $odd")	//11
odd = 12	//false가 return되어 값 변경이 안 됨
println("odd = $odd")	//11
반응형

'Kotlin' 카테고리의 다른 글

data class  (0) 2022.05.06
연산자 함수, 오버로딩  (0) 2022.05.05
전개 연산자 *  (0) 2022.05.05
생성자 (constructor)  (0) 2022.04.30
생성자 역할을 하는 Factory 함수  (0) 2022.04.30