美文网首页kotlin
05设计模式-kotlin-单例模式Singleton

05设计模式-kotlin-单例模式Singleton

作者: xieyangxuejun | 来源:发表于2018-07-08 00:05 被阅读0次

    什么是单例模式

    一句话说: 在程序中只存在一个实例.

    直接代码

    /**
     * Created by silen on 2018/7/7 23:30
     * Copyright (c) 2018 in FORETREE
     */
    
    //懒汉式
    class S1 private constructor() {
        companion object {
            private var mInstance: S1? = null
    
            fun getInstance(): S1? {
                if (mInstance == null) {
                    mInstance = S1()
                }
                return mInstance
            }
        }
    }
    //线程安全
    class S2 private constructor() {
    
        companion object {
            private var mInstance: S2? = null
    
            @Synchronized fun getInstance(): S2? {
                if (mInstance == null) {
                    mInstance = S2()
                }
                return mInstance
            }
        }
    }
    
    //饿汉式
    class S3 private constructor() {
        companion object {
            @JvmStatic private val instance = S3()
    
            fun getInstance(): S3 {
                return instance
            }
        }
    }
    
    //双重检测 DCL
    class SDCL private constructor() {
        companion object {
            private var instance: SDCL? = null
    
            fun getInstance(): SDCL? {
                if (instance == null) {
                    synchronized(SDCL::class.java) {
                        if (instance == null) {
                            instance = SDCL()
                        }
                    }
                }
                return instance
            }
        }
    }
    
    //静态内部类
    class Sin private constructor() {
        companion object {
            fun getInstance():Sin {
                return SHolder.holder
            }
        }
    
        class SHolder private constructor() {
            companion object {
                val holder = Sin()
            }
        }
    }
    
    fun main(args: Array<String>) {
        println("饿汉式 equal : ${S1.getInstance()==S1.getInstance()} ")
        println("线程安全 equal : ${S2.getInstance()==S2.getInstance()} ")
        println("懒汉式 equal : ${S3.getInstance()==S3.getInstance()} ")
        println("双重检测 equal : ${SDCL.getInstance()==SDCL.getInstance()} ")
        println("静态内部类 equal : ${Sin.getInstance()==Sin.getInstance()} ")
    }
    

    运行结果

    饿汉式 equal : true 
    线程安全 equal : true 
    懒汉式 equal : true 
    双重检测 equal : true 
    静态内部类 equal : true 
    

    注意的是构造方法一定要私有化.

    QQ群:462546711

    相关文章

      网友评论

        本文标题:05设计模式-kotlin-单例模式Singleton

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