Created
July 2, 2020 12:27
-
-
Save hjhjw1991/35d227cdb95ad69f55199ed6e4ebd91a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hjhjw1991 | |
/** | |
* 带参数单例实现, 可复用 | |
* 定义 | |
* class ToSingle(arg: Any){ | |
* companion object: SingletonHolder<ToSingle, Any> ({arg -> doInit(arg)}) | |
* } | |
* 使用 | |
* ToSingle.getInstance(arg).xxx | |
* @author huangjun.barney | |
* @since 2020-05-14 | |
*/ | |
open class SingletonHolder<out T: Any, 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) { | |
var i2 = instance | |
if (i2 != null) { | |
i2 | |
} else { | |
val created = creator!!(arg) | |
instance = created | |
creator = null | |
created | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment