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? {
// 開啟事務(wù)
beginTransaction()
try {
val result = method.invoke(target, *args)
// 提交事務(wù)
commitTransaction()
return result
} catch (e: Exception) {
// 回滾事務(wù)
rollbackTransaction()
throw e
}
}
private fun beginTransaction() {
// 實現(xiàn)事務(wù)開啟邏輯
}
private fun commitTransaction() {
// 實現(xiàn)事務(wù)提交邏輯
}
private fun rollbackTransaction() {
// 實現(xiàn)事務(wù)回滾邏輯
}
}
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 {
// 實現(xiàn)權(quán)限檢查邏輯
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 代理模式在不同場景下實現(xiàn)橫切關(guān)注點(cross-cutting concerns),從而提高代碼的可維護性和可重用性。