代理(Proxy)

是一种设计模式。通过代理访问目标对象,扩展对象的功能,多余的功能交给代理实现

1.静态代理

定义interface与Impl,代理实现interface,通过代理实现impl对象

可以在不修改目标类的前提下,对目标进行扩展

public class PeopleHandler implements InvocationHandler {
    private Object obj;
    
    public PeopleHandler(Object obj) {
        this.obj = obj;
    }

    public Object getProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before invoke...");
        Object result = method.invoke(obj, args);
        System.out.println("after invoke...");
        return result;
    }

}

PeopleHandler(Object obj):通过被代理对象创建handler;

getProxy(Object obj):通过被代理对象创建代理;

invoke(Object proxy, Method method, Object[] args):代理不直接调用invoke,而是使用正常的方法时都会走invoke方法;

public class TestProxy {
    public static void main(String[] args) {
        //1.直接调用
        System.out.println("直接调用:");
        People people = new Student();
        people.work();
        
        //2.通过代理调用
        System.out.println("\n通过代理调用:");
        PeopleHandler handler = new PeopleHandler(people);
        People proxy = (People) handler.getProxy(people);
        proxy.work();
    }
}

 

2.动态代理

动态代理不需要实现接口

利用JDK的API,在内存中构建对象 java.lang.reflect.Proxy, 使用newProxyInstance方法

//给目标对象生成代理对象

public Object getProxyInstance() {

return Proxy.newProxyInstance(

target.getClass().getClassLoader(),

target.getClass().getInterfaces(),

new InvocationHandler() {

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

System.out.println("开始事务2");

//执行目标对象方法

Object returnValue = method.invoke(target, args);

System.out.println("提交事务2");

return returnValue;

}

}

);

Cglib代理

当代理类没有实现接口时,可以使用子类代理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值