前言
在Kotlin中,使用建造者模式来封装一个类有以下几个好处:
简化对象的创建过程:使用建造者模式可以将复杂的对象创建过程分解为多个简单的步骤,使得代码更加清晰易读。通过链式调用,可以按需设置对象的属性,而不需要记住每个属性的顺序和参数。
提供可选参数:建造者模式可以让你在创建对象时只设置必要的参数,而将其他参数设置为可选。这样可以避免创建多个构造函数或者使用大量的重载方法。
保证对象的一致性:建造者模式可以确保在对象创建过程中,对象始终处于一致的状态。在每个步骤中,可以进行必要的验证和处理,以确保对象的属性符合要求。
支持不可变性:通过将对象的属性设置为只读,建造者模式可以创建不可变的对象。这样可以提高代码的安全性和线程安全性。
可扩展性:如果需要添加新的属性或者修改现有属性,只需要在建造者类中添加相应的方法即可,而不需要修改已有的代码。这样可以降低代码的耦合性,并且方便后续的扩展和维护。
示例代码为:
class LogRYB private constructor(
private val rootPath: String,
private val errorPath: String?,
private val userInterceptor: (String) -> Unit,
private val ptlInterceptor: (String) -> Unit,
private val apiInterceptor: (String) -> Unit
) {
private const val TAG = "RYBApp"
private var level = Level.Info
private var mUserName = "" // BaseFunction.getNowUser() 写入日志文件用,标志谁操作
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
// 私有构造函数,防止外部直接实例化
private LogRYB() {}
// 静态内部类作为建造者
class Builder {
private var rootPath: String? = null
private var errorPath: String? = null
private var userInterceptor: (String) -> Unit = {}
private var ptlInterceptor: (String) -> Unit = {}
private var apiInterceptor: (String) -> Unit = {}
fun setRootPath(rootPath: String): Builder {
this.rootPath = rootPath
return this
}
fun setErrorPath(errorPath: String?): Builder {
this.errorPath = errorPath
return this
}
fun setUserInterceptor(interceptor: (String) -> Unit): Builder {
this.userInterceptor = interceptor
return this
}
fun setPtlInterceptor(interceptor: (String) -> Unit): Builder {
this.ptlInterceptor = interceptor
return this
}
fun setApiInterceptor(interceptor: (String) -> Unit): Builder {
this.apiInterceptor = interceptor
return this
}
// 构建并返回 LogRYB 实例
fun build(): LogRYB {
requireNotNull(rootPath) { "RootPath must be set" }
return LogRYB(rootPath, errorPath, userInterceptor, ptlInterceptor, apiInterceptor)
}
}
// 初始化日志的方法移到内部,由建造者调用
private fun initLogPath(rootPath: String, errorPath: String?) {
// 初始化日志文件保存路径的逻辑
}
// 用户日志方法保持不变
fun userLog(
message: String,
tag: String = TAG,
userName: String = mUserName,
status: Boolean = false
) {
log(message, tag)
scope.launch {
writeLog("【用户: $userName】 [$message], [状态: ${if (status) "成功" else "失败"}]")
mUserInterceptor(message)
}
}
// 其他方法和属性保持不变
}
// 使用示例
fun main() {
val logRYB = LogRYB.Builder()
.setRootPath("/path/to/logs")
.setErrorPath("/path/to/error/logs")
.setUserInterceptor { message ->
// 处理用户日志的逻辑
}
.setPtlInterceptor { message ->
// 处理PTL日志的逻辑
}
.setApiInterceptor { message ->
// 处理API日志的逻辑
}
.build()
logRYB.userLog("This is a user log message")
}