设计模式:(kotlin)----代理模式---动态代理

本文通过Kotlin代码展示了如何使用动态代理实现设计模式。示例中,handler类和Smart类作为代理模式的一部分,实现了在执行特定操作前后添加额外的行为,如打印日志。运行结果显示了代理模式在实际操作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码示例:

package com.lyc.myeight.interfaces

interface ZuFang {
        fun KanFang()
        fun DingJia(int: Int)
        fun QianHeTong()
}
package com.lyc.myeight

import android.util.Log
import com.lyc.myeight.interfaces.ZuFang

class Fangdong:ZuFang {
    companion object{
        val TAG="testlyc"
    }
    override fun KanFang() {
        Log.d(TAG,"kan")
    }

    override fun DingJia(int: Int) {
        Log.d(TAG,"一个月租金: $int")
    }

    override fun QianHeTong() {
        Log.d(TAG,"签合同")
    }
}

handler类:

package com.lyc.myeight

import android.util.Log
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method

class ZhongJieHandler :InvocationHandler{
    private var mTarget:Any?=null
    constructor(target: Any){
        this.mTarget=target
    }
    override fun invoke(p0: Any?, p1: Method?, p2: Array<out Any>?): Any? {
        Log.d("testlyc", "执行前")
        var result:Any?=null
        if (p1 != null) {
            result = p1.invoke(mTarget, *p2.orEmpty())
        }
       Log.d("testlyc", "执行后")
        return result
    }
}

Smart类:

package com.lyc.myeight

import com.lyc.myeight.interfaces.ZuFang
import java.lang.reflect.Proxy

class ZhongJieSmart {
    var mzuFang:ZuFang?=null
    constructor(zuFang: ZuFang){
        this.mzuFang=zuFang
        mzuFang=Proxy.newProxyInstance(
            zuFang.javaClass.classLoader,
            arrayOf(ZuFang::class.java),
            ZhongJieHandler(mzuFang!!)
        ) as ZuFang
    }
}

运行结果:

2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行前
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: kan
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行后
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行前
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 一个月租金: 300
2022-06-30 14:51:32.299 15381-15381/com.lyc.myeight D/testlyc: 执行后
2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 执行前
2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 签合同
2022-06-30 14:51:32.300 15381-15381/com.lyc.myeight D/testlyc: 执行后

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值