版權(quán)聲明:本文為原創(chuàng)文章,未經(jīng)允許不得轉(zhuǎn)載。
不帶參數(shù)
第一種
public class SingleCase private constructor() {
private object Holder { val INSTANCE = SingleCase () }
companion object {
val instance: SingleCase by lazy { Holder.INSTANCE }
}
var b:String? = null
}
第二種
public class SingleCase private constructor() {
companion object {
val instance: = SingleCase ()
}
var b:String? = null
}
第三種
public class SingleCase private constructor() {
companion object {
/*單例*/
@Volatile
private var INSTANCE: SingleCase ? = null
/*獲取單例*/
val instance: SingleCase
get() {
if (INSTANCE == null) {
synchronized(SingleCase ::class.java) {
if (INSTANCE == null) {
INSTANCE = SingleCase ()
}
}
}
return INSTANCE!!
}
}
}
...
帶參數(shù)
class SingleCase private constructor(str: String) {
var string: String = str;
companion object {
@Volatile
var instance: SingleCase ? = null
fun getInstance(c: String): SingleCase {
if (instance == null) {
synchronized(SingleCase ::class) {
if (instance == null) {
instance = SingleCase (c)
}
}
}
return instance!!
}
}
}
總結(jié)
這些也只是我在開發(fā)過程中發(fā)現(xiàn)和總結(jié)的東西,如果誰有更好的方法記得留言或者郵箱(1732685009@qq.com)
版權(quán)聲明:本文為原創(chuàng)文章,未經(jīng)允許不得轉(zhuǎn)載。