代理模式与Java动态代理

xiaoxiao2021-02-28  59

一、代理模式介绍

代理模式:为其他对象提供一种代理以便控制对这个对象的访问。

可以详细控制访问某个类(对象)的方法,在调用这个方法前作的前置处理(统一的流程代码放到代理中处理)。调用这个方法后做后置处理。

二、静态代理:

public class Proxy { public static void main(String[] args) { Interface anInterface = new ProxyInterface(new RealImpl()); anInterface.sayHello(); }}interface Interface { void sayHello();}class RealImpl implements Interface { public void sayHello() { System.out.println("hello,everyone!"); }}class ProxyInterface implements Interface { private Interface anInterface ; public ProxyInterface(Interface anInterface) { this.anInterface = anInterface; } public void sayHello() { System.out.println("---------"); anInterface.sayHello(); System.out.println("=========="); }} 输出:

--------- hello,everyone! ========== 三、Java动态代理: Java自动给我们生成一个代理类,但是我们需要提供一个实现了 InvocationHandler接口的类,在这个invoke方法里面进行相应的代理逻辑实现, 当生成代理类之后,代理类会生成接口里面的相应的方法,然后把实际的调用转到invoke方法的调用。 public class DynamicProxyTest { public static void main(String[] args) { Impl real = new Impl(); ProxyedInterface proxy = (ProxyedInterface)Proxy.newProxyInstance(ProxyedInterface.class.getClassLoader(), new Class[]{ProxyedInterface.class}, new ProxyHandler(real)); proxy.sayHello(); }}interface ProxyedInterface { void sayHello();}class Impl implements ProxyedInterface { public void sayHello() { System.out.println("hello,everyone!"); }}class ProxyHandler implements InvocationHandler { private Object proxied = null; public ProxyHandler(Object proxied){ this.proxied = proxied; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---------"); method.invoke(proxied, args); System.out.println("=========="); return null; }} 输出: --------- hello,everyone! ========== 1 、代理生成了,那么想想如果我们在第一个输出语句和第二个输出语句里面做点什么操作,是不是就能实现AOP的功能呢? 2、这个地方我们可以再扩展一下,如果我们的 ProxyHandler不传入实际的被代理对象,也就是说执行invoke方法的时候直接自己代码实现,而不再写 method.invoke(proxied, args)代码。我们的ProxyHandler可以改造为: class ProxyHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---------"); //TODO:特殊的业务逻辑 System.out.println("=========="); return null; }} 想一下,我们在mybatis的时候,我们只需要定义接口和mapper文件,然后使用 @Autowired进行自动植入,发现我们就能执行相应的SQL,是不是就可以使用上面的这个handler实现呢?
转载请注明原文地址: https://www.6miu.com/read-2400137.html

最新回复(0)