Kotlin 中的单例

Kotlin 中的单例

以获取 Application 的单例来说明

在 java 中的单例

public class App extends Application {

    private static App instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static App getInstance(){
        return instance;
    }
}

在 Kotlin 中的单例

第一种,仿照 java 中的写法

  class App : Application() {

    companion object {
       private var instance: App? = null
        fun instance() = instance
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

第二种,使用 Kotlin 自带的单例模式,使用 notNull 委托


    companion object {
      var instance: App by Delegates.notNull()
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

第三种,Kotlin 库提供了几个接口,我们自己的委托必须要实现的几个接口,自定义单例模式,创建一个 DelegatesExt.kt 文件

object DelegatesExt {
    //现在你可以创建一个对象,然后添加函数使用你的委托:
    fun <T> notNullSingleValue(): ReadWriteProperty<Any?, T> = NotNullSingleValueVar()
    fun <T> getPreference(context: Context, 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin创建PopupWindow的单例可以通过以下步骤实现: 1. 创建一个名为PopupWindowSingleton的Kotlin对象,该对象将作为PopupWindow的单例。 2. 在PopupWindowSingleton对象声明一个私有的PopupWindow变量,用于保存单例的实例。 3. 在PopupWindowSingleton对象声明一个公共的getInstance()方法,用于获取PopupWindow的单例实例。 4. 在getInstance()方法,检查PopupWindow实例是否已经被创建。如果已经创建,则直接返回该实例;如果尚未创建,则创建一个新的PopupWindow实例并保存到变量。 5. 在getInstance()方法,设置PopupWindow的属性,例如宽度、高度、背景等。 6. 在getInstance()方法,返回PopupWindow的单例实例。 以下是一个示例代码: ```kotlin class PopupWindowSingleton private constructor() { private var popupWindow: PopupWindow? = null companion object { private var instance: PopupWindowSingleton? = null fun getInstance(): PopupWindowSingleton { if (instance == null) { instance = PopupWindowSingleton() instance?.popupWindow = PopupWindow() // 设置PopupWindow的属性 instance?.popupWindow?.width = WindowManager.LayoutParams.WRAP_CONTENT instance?.popupWindow?.height = WindowManager.LayoutParams.WRAP_CONTENT instance?.popupWindow?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } return instance!! } } fun showPopupWindow(view: View) { // 显示PopupWindow instance?.popupWindow?.showAsDropDown(view) } } ``` 使用时,可以通过调用PopupWindowSingleton.getInstance()方法获取PopupWindow的单例实例,并调用showPopupWindow()方法显示PopupWindow。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值