Kotlin 自带的Builder建造者模式
发布日期:2021-05-10 09:30:24 浏览次数:16 分类:精选文章

本文共 2150 字,大约阅读时间需要 7 分钟。

Kotlin Builder������������

Kotlin������Builder���������������������Java������������������������������������������������������������

Method 1: ���������������������

  • ���������������������������������������������������
  • class Person {
    var name = ""
    var age = 0
    var married = false
    override fun toString(): String {
    return "Person(name='$name', age=$age, married=$married)"
    }
    }
    1. ������������������������������:
    2. val person = Person().apply {
      name = "zhk"
      age = 18
      married = false
      }
      Log.i("Test", person.toString())
      1. ������������������:
      2. I/Test: Person(name='zhk', age=18, married=false)

        Method 2: ��� ��lindi��res���������

      3. ������������������������������������:
      4. class MyDialog {
        private var tvTitle: TextView? = null
        private var tvContent: TextView? = null
        init {
        val layoutInflater = LayoutInflater.from(Global.getContext())
        val rootView = layoutInflater.inflate(R.layout.dialog_avatar, null)
        tvTitle = rootView.findViewById(R.id.tv_title)
        tvContent = rootView.findViewById(R.id.tv_content)
        }
        fun title(@StringRes res: Int? = null, text: CharSequence? = null): MyDialog {
        if (res != null) {
        this.tvTitle?.text = Global.getContext().getString(res)
        } else if (text != null) {
        this.tvTitle?.text = text
        }
        return this
        }
        fun content(@StringRes res: Int? = null, text: CharSequence? = null): MyDialog {
        if (res != null) {
        this.tvContent?.text = Global.getContext().getString(res)
        } else if (text != null) {
        this.tvContent?.text = text
        }
        return this
        }
        inline fun show(func: MyDialog.() -> Unit) {
        this.func()
        this.show()
        }
        fun show() {
        // ...
        }
        }
        1. ������������:
        2. MyDialog().show {
          title(res = R.string.login_title)
          content(text = "������XXXX")
          }

          Method 3:DSL������

          ��������������� nltki-craftsmen���������������Kotlin������������������������������������

          ������

          ���������������������������Kotlin Builder������������������������������������������������������������������������������������������������������

    上一篇:Android DEX加固方案与原理
    下一篇:Android 中的字体大小适配

    发表评论

    最新留言

    关注你微信了!
    [***.104.42.241]2025年04月23日 23时22分23秒