美文网首页
Kotlin带参数的单例

Kotlin带参数的单例

作者: chandarlee | 来源:发表于2018-07-31 07:41 被阅读272次

    单例包装类

    open class SingletonHolder<out T, in A>(creator: (A) -> T) {
        private var creator: ((A) -> T)? = creator
        @Volatile private var instance: T? = null
    
        fun getInstance(arg: A): T {
            val i = instance
            if (i != null) {
                return i
            }
    
            return synchronized(this) {
                val i2 = instance
                if (i2 != null) {
                    i2
                } else {
                    val created = creator!!(arg)
                    instance = created
                    creator = null
                    created
                }
            }
        }
    }
    

    使用如下

    class Manager private constructor(context: Context) {
        init {
            // Init using context argument
        }
    
        companion object : SingletonHolder<Manager, Context>(::Manager)
    }
    
    Manager.getInstance(context).doStuff()
    

    无参构造函数的单例模式

    interface GitHubService {
    
        companion object {
            val instance: GitHubService by lazy {
                val retrofit = Retrofit.Builder()
                        .baseUrl("https://api.github.com/")
                        .build()
                retrofit.create(GitHubService::class.java)
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Kotlin带参数的单例

          本文链接:https://www.haomeiwen.com/subject/gaccvftx.html