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),從而提高代碼的可維護性和可重用性。