天天看點

Kotlin中使用DSL方式實作接口回調

import log
import sun.audio.AudioData

class AudioPlayer{
    //定義一個内部類
    inner class ListenerBuilder{
        //定義三個回調方法
        internal var mAudioPlayAction:((AudioData) -> Unit)? = null
        internal var mAudioPauseAction:((AudioData) -> Unit)? = null
        internal var mAudioFinishAction:((AudioData) -> Unit)? = null
        fun onAudioPlay(action:(AudioData) -> Unit){
            mAudioPlayAction = action
        }

        fun onAudioPause(action: (AudioData) -> Unit){
            mAudioPauseAction = action
        }

        fun onAudioFinish(action: (AudioData) -> Unit){
            mAudioFinishAction = action
        }
    }

    lateinit var mListener:ListenerBuilder
    //提供方法供外部實作接口的回調監聽
    fun registerListener(listenerBuilder: ListenerBuilder.() -> Unit){
        mListener = ListenerBuilder().also(listenerBuilder)
    }
}

fun main(){
    val audioPlayer = AudioPlayer()
    audioPlayer.registerListener {
        onAudioPlay {
            log("onAudioPlay")
        }
        onAudioPause {
            log("onAudioPause")
        }
        onAudioFinish {
            log("onAudioFinish")
        }
    }

    audioPlayer.mListener.mAudioPlayAction?.invoke(AudioData(byteArrayOf()))
    audioPlayer.mListener.mAudioPauseAction?.invoke(AudioData(byteArrayOf()))
    audioPlayer.mListener.mAudioFinishAction?.invoke(AudioData(byteArrayOf()))
}
           

繼續閱讀