• 静态代理和动态代理


    静态代理

    为某个对象提供一个代理,以控制对这个对象的访问。 代理类和被代理类有共同的父类或父接口,这样在任何使用被代理类对象的地方都可以用代理对象替代。代理类负责请求的预处理、过滤、将请求分派给被代理对象处理、以及被代理对象执行完请求后的后续处理。

    代理类是手动编写的代码,在编译期代理类和被代理类的关系就确定了。

    public class StaticProxy {
    
    	public static void main(String[] args) {
    		Sell mall=new ClothMall(new NikeFactory());
    		double price = mall.sell();
    		System.out.println("商场卖出商品的价格:"+price);
    	}
    }
    
    interface Sell{
    	double sell();
    }
    
    //被代理对象
    class NikeFactory implements Sell{
    	@Override
    	public double sell() {
    		return 100;
    	}
    }
    
    //代理对象
    class ClothMall implements Sell{
    	//被代理对象
    	private Sell target;
    	public ClothMall(Sell target) {
    		this.target=target;
    	}
    	
    	@Override
    	public double sell() {
    		double originalPrice = target.sell();
    		//提价
    		return originalPrice+50;
    	}
    	
    }
    
    

    动态代理

    动态代理类的源码是在程序运行期间由JVM根据反射等机制动态的生成,所以不存在代理类的字节码文件。代理类和被代理类的关系是在程序运行时确定。

    public class DynamicProxy {
    
    	public static void main(String[] args) {
    
    		ProxyFactory proxyFactory=new ProxyFactory(new HouseOwner());
    		RentHouse proxy = (RentHouse)proxyFactory.getProxyInstance();
    		double price = proxy.rentHouse();
    		System.out.println("代理出租房子价格:"+price);
    		
    		ProxyFactory proxyFactory2=new ProxyFactory(new NikeFactory());
    		Sell proxy2 = (Sell)proxyFactory2.getProxyInstance();
    		double price2 = proxy2.sell();
    		System.out.println("代理出售Nike服装价格:"+price2);
    	}
    }
    
    interface RentHouse {
    	double rentHouse();
    }
    
    //被代理对象
    class HouseOwner implements RentHouse {
    	@Override
    	public double rentHouse() {
    		return 1500;
    	}
    }
    
    class ProxyFactory implements InvocationHandler {
    
    	//被代理对象
    	private Object target;
    	public ProxyFactory(Object target) {
    		this.target=target;
    	}
    	
    	@Override
    	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    		double originalPrice = (double)method.invoke(target, args);
    		//后置操作,提价
    		return originalPrice+100;
    	}
    	
    	//返回代理类对象
    	public Object getProxyInstance() {
    		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    	}
    }
    

    在动态代理中,不用去手动编写代理类,可以根据代理工厂为每个被代理类生成一个代理类,在被代理类较多时,可以减少代理类的编写。

  • 相关阅读:
    python进阶之装饰器之3利用装饰器强制函数上的类型检查
    python进阶之装饰器之6.装饰器为被包装函数增加参数,如何实现装饰器对类进行打补丁或者说对类的功能进行扩充
    python进阶之装饰器之5把装饰器作用到类和静态方法上
    python进阶之装饰器之4在类中定义装饰器,将装饰器定义为类,两者的区别与联系
    AOP的使用
    使用Maven搭建SSM框架
    js判断字符串是否有重复
    纯js实现复制功能
    关于Log文本的操作
    jquery往textarea鼠标光标选中的地方插入值
  • 原文地址:https://www.cnblogs.com/moyuduo/p/13097653.html
Copyright © 2020-2023  润新知