单利模式有多种,其实并不需要那么多。java里面分,懒汉,饿汉,DSL,内部类,枚举,加syncronized的懒汉 等
其实最有效有用的,DSL ,枚举,内部类这三种
java
内部类
public class SingletonManager {
private SingletonManager() {
}
public static SingletonManager getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder{
private final static SingletonManager instance = new SingletonManager();
}
}
Enum
public class SingletonManager {
private SingletonManager() {
}
public static SingletonManager getInstance(){
return SingletonEnum.INSTANCE.getSingletonManager();
}
private enum SingletonEnum{
INSTANCE;
private SingletonManager singletonManager = null;
private SingletonEnum(){
singletonManager = new SingletonManager();
System.out.println("enum=======constructor");
}
private SingletonManager getSingletonManager(){
System.out.println("getinstance");
return singletonManager;
}
}
}
kotlin 照着java也有对应的多种,但是在kotlin中只有一种推荐,就是Object
DSL
public class SingletonManager {
private SingletonManager() {
}
private volatile static SingletonManager singletonManager;
public static SingletonManager getInstance() {
if (singletonManager == null) {
synchronized (SingletonManager.class) {
if (singletonManager == null) {
singletonManager = new SingletonManager();
}
}
}
return singletonManager;
}
}
剩下懒汉,饿汉,不推荐用,太简单不列举
kotlin
object SingletonDemo
DSL
class SingletonDemo private constructor(){
companion object{
val instance:SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonDemo()
}
}
}
class SingletonDemo private constructor(private val property: Int) {//这里可以根据实际需求发生改变
companion object {
@Volatile private var instance: SingletonDemo? = null
fun getInstance(property: Int) =
instance ?: synchronized(this) {
instance ?: SingletonDemo(property).also { instance = it }
}
}
}
不推荐
懒汉线程安全
class SingletonDemo private constructor(){
companion object{
private var instance:SingletonDemo? = null
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
@Synchronized
fun get():SingletonDemo{
return instance!!
}
}
}
类似内部类,不推荐
class SingletonDemo private constructor(){
companion object{
val instance = SingletonHolder.holder
}
private object SingletonHolder{
val holder = SingletonDemo()
}
}
网友评论