【Kotlin设计模式】建造者模式在Android中的应用

前言

建造者模式(Builder Pattern)是一种创建型设计模式,一步一步地构建一个复杂对象的不同部分,而不是直接创建该对象的实例。建造者模式的核心思想是将对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。

具体来说,构建者模式使用一个独立的构建器(Builder)类来封装对象的构建过程。构建器类提供一系列方法来设置对象的属性,并最终返回构建好的对象。这种方式可以避免使用多个构造函数或过多的参数,使得对象的构建过程更加直观和易于扩展。

应用

Android中,也有很多组件和库中使用到了建造者模式,比如原生AlertDialogRetrofitNotificationCompat等。

AlertDailog中应用:

kotlin 复制代码
val builder = AlertDialog.Builder(this)
builder.setTitle("设计模式")
       .setMessage("这是建造者模式吗")
       .setPositiveButton("是的") { dialog, _ -> dialog.dismiss() }
       .setNegativeButton("不是") { dialog, _ -> dialog.dismiss() }
       .create()
       .show()
       

Retrofit中应用:

kotlin 复制代码
val retrofit = Retrofit.Builder()
    .baseUrl("https://blog.csdn.net/ho")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val apiService = retrofit.create(ApiService::class.java)

从上述例子可以看出,建造者模式的写法比较清晰,比如AlertDailog中的builder对象采用链式调用setTitlesetMessage等方法,我们就仿照AlertDailog使用Kotlin来实现下建造者模式。

kotlin 复制代码
package com.ho.csdn.widget

import android.app.Dialog
import android.content.Context
import android.graphics.Bitmap
import java.lang.IllegalArgumentException


class StudentPickDialog(context: Context) : Dialog(context) {

    private var mId: Long = 0L

    private var mAvatar: Bitmap? = null

    private var mName: String = ""

    private var mAge: Int = 0

    private constructor(
        context: Context,
        id: Long,
        avatar: Bitmap?,
        name: String,
        age: Int
    ) : this(context) {
        mAvatar = avatar
        mId = id
        mName = name
        mAge = age
    }

    companion object {

        fun init(context: Context): Builder {
            return Builder(context)
        }
    }


    data class Builder(private val mContext: Context) {

        private var mId: Long = 0L

        private var mAvatar: Bitmap? = null

        private var mName: String = ""

        private var mAge: Int = 0

        /**
         * 设置id
         */
        fun setId(id: Long) = apply {
            this.mId = id
        }

        /**
         * 设置头像
         */
        fun setAvatar(avatar: Bitmap) = apply {
            this.mAvatar = avatar
        }

        /**
         * 设置名称
         */
        fun setName(name: String) = apply {
            this.mName = name
        }

        /**
         * 设置年龄
         */
        fun setAge(age: Int) = apply {
            this.mAge = age
            if (mAge > 150) {
                throw IllegalArgumentException("年龄超过了限制")
            }
        }

        fun build() = StudentPickDialog(mContext, mId, mAvatar, mName, mAge)
    }
}

这里自定义Dailog显示选择某一学生信息做展示,建造者模式部分如下,新建StudentPickDialog继承Dialog,在类内部新建Builder类,创建setAvatarsetNamesetAge且返回Builder对象,外部创建了Builder对象后就可以链式调用方法了。

这里使用到了Kotlin的apply扩展函数,函数返回调用它的对象本身的特性。

新建build()方法,返回StudentPickDialog对象,将Id、名字、头像、年龄作为构造参数传入,调用如下。

kotlin 复制代码
   StudentPickDialog
          .init(requireContext())
          .setId(92229)
          .setAvatar(detectBitmap!!)
          .setName("Ho")
          .setAge(30)
          .build()
          .show()
          

总结

Android 中,建造者模式被广泛应用于需要配置多个选项、步骤复杂或构建过程不容易一步完成的场景。通过建造者模式,可以更轻松地创建和配置复杂对象。

相关推荐
积跬步DEV4 小时前
Android 获取签名 keystore 的 SHA1和MD5值
android
陈旭金-小金子6 小时前
发现 Kotlin MultiPlatform 的一点小变化
android·开发语言·kotlin
二流小码农8 小时前
鸿蒙开发:DevEcoStudio中的代码提取
android·ios·harmonyos
牛奶咖啡138 小时前
学习设计模式《十三》——迭代器模式
设计模式·迭代器模式·内部迭代器和外部迭代器·带迭代策略的迭代器·双向迭代器·迭代器模式的优点·何时选用迭代器模式
哆啦A梦的口袋呀8 小时前
设计模式汇总
python·设计模式
江湖有缘9 小时前
使用obsutil工具在OBS上完成基本的数据存取【玩转华为云】
android·java·华为云
移动开发者1号10 小时前
Android 多 BaseUrl 动态切换策略(结合 ServiceManager 实现)
android·kotlin
移动开发者1号10 小时前
Kotlin实现文件上传进度监听:RequestBody封装详解
android·kotlin
在未来等你11 小时前
设计模式精讲 Day 1:单例模式(Singleton Pattern)
java·设计模式·面向对象·软件架构
不会编程的小江江11 小时前
【设计模式】单例模式
单例模式·设计模式