Kotlin 代理模式可以用于许多场景,以下是一些常见的用途:
class LoggingProxy(private val target: Any) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>): Any? {
println("Before method call: ${method.name}")
val result = method.invoke(target, *args)
println("After method call: ${method.name}")
return result
}
}
class TransactionProxy(private val target: Any) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>): Any? {
// 开启事务
beginTransaction()
try {
val result = method.invoke(target, *args)
// 提交事务
commitTransaction()
return result
} catch (e: Exception) {
// 回滚事务
rollbackTransaction()
throw e
}
}
private fun beginTransaction() {
// 实现事务开启逻辑
}
private fun commitTransaction() {
// 实现事务提交逻辑
}
private fun rollbackTransaction() {
// 实现事务回滚逻辑
}
}
class PermissionProxy(private val target: Any) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>): Any? {
if (hasPermission()) {
return method.invoke(target, *args)
} else {
throw SecurityException("Permission denied")
}
}
private fun hasPermission(): Boolean {
// 实现权限检查逻辑
return true
}
}
class CachingProxy(private val target: Any) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any?>): Any? {
val cacheKey = method.name + Arrays.toString(args)
val cachedResult = cache.get(cacheKey)
if (cachedResult != null) {
return cachedResult
}
val result = method.invoke(target, *args)
cache.put(cacheKey, result)
return result
}
private val cache = ConcurrentHashMap<String, Any?>()
}
这些示例展示了如何使用 Kotlin 代理模式在不同场景下实现横切关注点(cross-cutting concerns),从而提高代码的可维护性和可重用性。