单例模式的优点:
在内存中只有一个对象,节约内存 避免频繁的创建和销毁对象,可以提高性能 避免对共享资源的多重占用 可以全局访问
适用场景:
需要频繁实例化然后销毁的对象 创建对象时,耗时过多或者耗资源过多,但又经常用到的对象 有状态的工具类对象 频繁访问数据库或文件的对象 要求只有一个对象的场景
1. 饿汉单例
public class Singleton {
private Singleton ( ) {
}
private static Singleton instance = new Singleton ( ) ;
public static Singleton getInstance ( ) {
return instance;
}
}
object Singleton {
}
2. 懒汉单例
public class Singleton {
private Singleton ( ) {
}
private static Singleton instance;
public static Singleton getInstance ( ) {
if ( instance != null) {
instance = new Singleton ( ) ;
}
return instance;
}
}
java懒汉线程安全,方法前加上了synchronized关键字
public class Singleton {
private Singleton ( ) {
}
private static Singleton instance;
public static synchronized Singleton getInstance ( ) {
if ( instance != null) {
instance = new Singleton ( ) ;
}
return instance;
}
}
class Singleton private constructor ( ) {
companion object {
private var instance: Singleton? = null
get ( ) {
if ( field == null ) {
field = Singleton ( )
}
return field
}
fun get ( ) : Singleton {
return instance!!
}
}
}
kotlin懒汉线程安全,多了一个Synchronized注解
class Singleton private constructor ( ) {
companion object {
private var instance: Singleton? = null
get ( ) {
if ( field == null ) {
field = Singleton ( )
}
return field
}
@Synchronized
fun get ( ) : Singleton {
return instance!!
}
}
}
3. 静态内部类单例
public class StaticInnerSingleton {
private StaticInnerSingleton ( ) {
}
private static class SingletonHolder {
private static final StaticInnerSingleton mInstance = new StaticInnerSingleton ( ) ;
}
public static StaticInnerSingleton getInstance ( ) {
return SingletonHolder. mInstance;
}
}
class Singleton private constructor ( ) {
companion object {
val instance = SingletonHolder. holder
}
private object SingletonHolder {
val holder= Singleton ( )
}
}
4. 双重校验锁(Double Check)
public class SingletonDemo {
private volatile static SingletonDemo instance;
private SingletonDemo ( ) { }
public static SingletonDemo getInstance ( ) {
if ( instance== null ) {
synchronized ( SingletonDemo. class) {
if ( instance== null ) {
instance= new SingletonDemo ( ) ;
}
}
}
return instance;
}
}
class SingletonDemo private constructor ( ) {
companion object {
val instance: SingletonDemo by lazy ( mode = LazyThreadSafetyMode. SYNCHRONIZED) {
SingletonDemo ( ) }
}
}
5. 枚举单例
public enum GetIatResult {
INSTANCE;
public void start ( ) {
}
}