静态代理和动态代理

本文详细介绍了代理模式的原理和应用,包括静态代理和动态代理。在静态代理中,通过创建代理类来扩展目标类的功能。而在动态代理中,利用Java的Proxy类和InvocationHandler接口,可以在运行时动态创建代理对象,实现更灵活的控制。文章通过代码示例展示了如何实现这两个代理方式,并在最后进行了总结。
摘要由CSDN通过智能技术生成


一、代理模式

代理设计就是为其他对象提供一种代理以控制对这个对象的访问

在这里插入图片描述

二、静态代理

工厂接口

interface ClothFactory {
    public void produceCloth();
}

被代理类

class NikeClothProduct implements ClothFactory{
    @Override
    public void produceCloth() {
        System.out.println("生产Nike服装");
    }
}

代理类

class ProxyClothFactory implements ClothFactory{
    private ClothFactory clothProduct;

    public ProxyClothFactory(ClothFactory clothProduct) {
        this.clothProduct = clothProduct;
    }

    @Override
    public void produceCloth() {
        System.out.println("生产前工作");
        clothProduct.produceCloth();
        System.out.println("生产后工作");
    }
}

主函数驱动测试

public class ClothProxyTest {
    public static void main(String[] args) {
        NikeClothProduct nikeClothProduct = new NikeClothProduct();
        ProxyClothFactory proxyClothFactory = new ProxyClothFactory(nikeClothProduct);
        proxyClothFactory.produceCloth();
    }
}

运行结果


在这里插入图片描述

三、动态代理

在这里插入图片描述

实现Invocation类,加入通用方法

class MyInvocationHandler implements InvocationHandler{
	//用于保存被代理类对象
    private Object obj;
    public void band(Object obj){
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //===============前置通用方法===========
        System.out.println("=============前置方法=============");
        //=====================================
        
        //===============原始方法==============
        Object returnVal = method.invoke(obj,args);
        //=====================================
       
        //===============后置通用方法===========
        System.out.println("=============后置方法=============");
        //=====================================
        return returnVal;
    }
}

通过Proxy类创建动态代理对象

先绑定被代理类
返回Proxy.newProxyInstance(被代理类的类加载器,被代理类的接口,InvocationHandler对象)

将其写入ProxyFactory代理类中

class ProxyFactor{
    public static Object getProxyInstance(Object obj){
        MyInvocationHandler handler = new MyInvocationHandler();
        handler.band(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
    }
}

使用

public class DynamicProxyTest {
    public static void main(String[] args) {
        SuperMan superMan = new SuperMan();
        //载入任何对象
        Human proxy = (Human) ProxyFactor.getProxyInstance(superMan);
        //调用任何对象的方法都会先使用代理类方法
        System.out.println(proxy.getBelief());
        proxy.eat("麻辣烫");
    }
}

在这里插入图片描述

总结

difficult

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值