◎筱米加步枪◎.Blog

Happy coding

代理模式-动态代理

筱米加步枪 posted @ 2010年8月31日 03:53 in [ 设计模式 ] with tags 设计模式 动态代理 , 1861 阅读

最近项目中一直在配置Spring AOP,听说AOP是基于动态代理模式实现的,于是乎就去学习了动态代理,虽然还是迷迷糊糊,不过还是将自己的学习成功总结下。

自己写了个例子来说明:(部分说明写在代码中)

//汽车类
public  class Car {
	
	//牌子
	private String brand;
	
	public Car(String brand){
		this.brand = brand;
	}
	
	//获取汽车的描述
	public  String getDescribe(){
		return brand+"车";
	}
}
//奥迪车
public class AudiCar extends Car{
	
	public AudiCar(){
		super("奥迪");
	}
}
//奔驰车
public class BenzCar extends Car {
	
	public BenzCar(){
		super("奔驰");
	}
}
//汽车代理接口
public interface CarProxy {
	
	public void sellCar(Car car);
}
//汽车代理实现类
public class CarProxyImpl implements CarProxy {

	@Override
	public void sellCar(Car car){
		System.out.println("卖出一辆"+car.getDescribe());
	}
}
//动态代理对象(调用处理器)-可代理任何的代理对象
//这个类是被java.lang.reflect.Proxy所调用
public class DynamicProxy implements InvocationHandler{
	
	//代理对象
	private Object proxyObject;
	
	public DynamicProxy(Object proxyObject){
		this.proxyObject = proxyObject;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		//方法执行前做事 Spring AOP 切面的原理 ,对方法method进行横切
		//在真正执行方法之前或者之后做一些额外的操作
		//就这就Spring AOP实现横向切面的原理了
		System.out.println("打算执行方法");
		Object object = method.invoke(proxyObject, args);
		//方法执行之后做的事,Spring AOP 切面的原理
		System.out.println("方法执行之后");
		return object;
	}
}
//代理工厂
public class ProxyFactory {

	// 创建一个代理
	public static Object createProxy(Object proxyObject) { // 被代理的对象
		Class<? extends Object> clazz = proxyObject.getClass();
		Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), clazz
				.getInterfaces(), new DynamicProxy(proxyObject));
		return proxy;
	}
}
//测试类
public class Test {
	
	public static void main(String[] args) {
		//通过代理工厂创建一个汽车代理
		CarProxy carProxy = (CarProxy) ProxyFactory
				.createProxy(new CarProxyImpl());
		carProxy.sellCar(new AudiCar());
		carProxy.sellCar(new BenzCar());
	}
}
打算执行方法
卖出一辆奥迪车
方法执行之后
打算执行方法
卖出一辆奔驰车
方法执行之后

动态代理的好处就是可以代理任意的代理对象,都可以通过代理工厂中指定代理对象即可。

另外就是可对执行方法加入一些额外操作,就是AOP了,只是Spring把这些都通过配置来实现。

jnanabhumiap.in 说:
2024年1月26日 20:43

JNANABHUMI AP provides all latest educational updates and many more. The main concept or our aim behind this website has been the will to provide resources full information on each topic which can be accessed through Internet. To ensure that every readers get’s what important and worthy about the topic they search and link to hear from us. jnanabhumiap.in Jnanabhumi AP is a startup by passionate webmasters and bloggers who have passion to provide engaging content which is accurate, interesting and worthy to read. We are mope like a web community where you can find different information’s, resources, topics on day to day incidents or news. We provide you the finest of web content on each and every topics possible with help of editorial and content team.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter