Spring 静态代理和动态代理(实现接口)

代理设计模式:通过代理完成目标对象的工作,同时代理还可以做自己的事情。
代理设计模式根据代理对象的生成时机分为两类:
A:静态代理:代理类在程序运行前已经存在了。
B:动态代理:代理类在程序运行过程中通过反射技术自动生成的,在程序运行之前是看到静态代理类的。
代理设计模式的实现方式:
A:如果目标类已经实现了某个接口,则代理类和目标类实现相同的接口并在代理类中持有目标类的引用,
JDK动态代理使用的就是这种方式。
B:如果目标类没有实现任何接口则生成代理类是目标类的子类,此时目标类一定不能是final类。

(静态代理)实现接口的例子:

public interface PersonDao {

	void add(String name);
}

public class PersonDaoBean implements PersonDao {

	@Override
	public void add(String name) {
		System.out.println(name+"完成添加Person对象的工作");
	}
}

public class PersonDaoProxyBean implements PersonDao {
private PersonDao personDao;
	public PersonDaoProxyBean(PersonDao personDao){
		this.personDao=personDao;
	}
	@Override
	public void add(String name) {
		this.validate();
		//调用目标类中的方法
		this.personDao.add(name);
		this.log();
}
		private void log() {
		System.out.println("增加添加日志的工作");
	}
private void validate() {
		System.out.println("数据校验工作!");
		}
}

测试类

public class TestPersonDaoDemo01 {

	public static void main(String[] args) {
		/*PersonDao personDao=new PersonDaoBean();
		personDao.add("张三");*/
		
		//目标对象
		PersonDao personDao=new PersonDaoBean();
		//在实例化代理对象是将目标对象作为参数传递到了代理对象中
		PersonDao personDaoProxy=new PersonDaoProxyBean(personDao);
		personDaoProxy.add("夏利");

	}

}

(动态代理)实现接口的例子:

public interface PersonDao {

	void add(String name);
	
	int minus(int a,int b);
}

public class PersonDaoBean implements PersonDao {

	@Override
	public void add(String name) {
		System.out.println(name+"完成添加Person对象的工作");
	}

	@Override
	public int minus(int a, int b) {
		int result=a-b;
		System.out.println("==PersonDaoBean.minus(int a="+a+", int b="+b+")===");
		return result;
	}
}

代理工厂

public class ProxyFactory {

	private Object target;

	public ProxyFactory(Object target) {
		this.target = target;
	}

	public Object getProxyIntances() {

		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("开始");
						Object result = method.invoke(target, args);
						System.out.println("结束");
						return result;
					}
				});
	}
}

测试类

public class TestStaticAgent {

	
	 public static void main(String[] args) throws Exception {
		
		 PersonDao target=new PersonDaoBean();
		
		 PersonDao proxy=(PersonDao) new ProxyFactory(target).getProxyIntances();
		
		 
		  Person person=new Person("KK", 15, "ni", new Date());
		  proxy.add(person);
		  int result=proxy.minus(5, 2);
		  System.out.println(result);
		 
		 
	}
	
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值