设计模式(2)_代理模式

1,收房租接口

public interface LandLordService {

    //收房租
    public void rent();
}

2,实现类

public class LandLord implements LandLordService {

    public void rent() {
            System.out.println("房东亲自收入房租");
    }
}

JDK动态代理

public class JdkProxy implements InvocationHandler {

    //要代理增强的对象
    private Object instance;

    public JdkProxy(Object instance) {
        this.instance = instance;
    }

    //使用此方法进行动态代理,使用此方法进行原方法的扩展
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("JDK动态代理开始");
        Object invoke = method.invoke(instance, args);
        System.out.println("JDK动态代理结束");
        return invoke;

    }
}

测试方法

public class JdkProxyTest {

    public static void main(String[] args){

        LandLordService landLord = new LandLord();
        //房东收房租
        landLord.rent();
        JdkProxy jdkProxy = new JdkProxy(landLord);
        LandLordService landLordProxy = ( LandLordService )Proxy.newProxyInstance(LandLord.class.getClassLoader(), landLord.getClass().getInterfaces(), jdkProxy);
        //动态代理类进行收房租
        landLordProxy.rent();
    }
}

测试结果

房东亲自收入房租
JDK动态代理开始
房东亲自收入房租
JDK动态代理结束

CgLib动态代理

public class CgLibProxy implements MethodInterceptor {

    //要代理增强的对象
    private Object instance;


    public CgLibProxy(Object instance) {
        this.instance = instance;
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("CgLib动态代理开始");
        Object invoke = method.invoke(instance, objects);
        System.out.println("CgLib动态代理结束");
        return invoke;
    }
}

测试方法

public class CglibProxyTest {

    public static void main(String[] args){

        LandLord landLord = new LandLord();
        landLord.rent();//房东收房租

        CgLibProxy cgLibProxy = new CgLibProxy(landLord);
        LandLord landLordProxy = (LandLord)Enhancer.create(LandLord.class, cgLibProxy);
        landLordProxy.rent();//动态代理收房租

    }
}

测试结论

Connected to the target VM, address: '127.0.0.1:61048', transport: 'socket'
房东亲自收入房租
Disconnected from the target VM, address: '127.0.0.1:61048', transport: 'socket'
CgLib动态代理开始
房东亲自收入房租
CgLib动态代理结束
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值