静态代理和动态代理

静态代理

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

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

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);
	}
}

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

原文地址:https://www.cnblogs.com/moyuduo/p/13097653.html