设计模式之动态代理模式

参考:

动态代理模式封装事务详解(举例简单易懂,图示清晰)

设计模式之 动态代理模式

彻底理解JAVA动态代理

Java动态代理一——动态类Proxy的使用 (与自己的代码很相似,简单明了)

代理模式(静态代理和动态代理)(很专业的样子,图示不太明朗,参考)
(Dynamic Proxy)动态代理模式的Java实现(写的很用心,时序图不错)

代理模式与Java 动态代理类 (好文要赞)

Spring AOP动态代理原理与实现方式 (不错,好文要赞)


动手实现代码:


package testProxyInvocationHandler;

import java.lang.reflect.Proxy;

public class TestClass {
	public static void main(String[] args) {
		// InvocationHandler实际处理目标类
		TargetInvocationHandler targetInvocationHandler = new TargetInvocationHandler();
		// 目标类
		TargetInterface target = new Target();
		// InvocationHandler调用目标类
		targetInvocationHandler.setTarget(target);

		ClassLoader loader = target.getClass().getClassLoader();
		Class[] interfaces = target.getClass().getInterfaces();

		// 代理类Proxy将目标类扔给InvocationHandler去处理
		TargetInterface targetProxy = (TargetInterface) Proxy.newProxyInstance(loader, interfaces, targetInvocationHandler);
		TargetInterface2 targetProxy2 = (TargetInterface2) Proxy.newProxyInstance(loader, interfaces, targetInvocationHandler);

		targetProxy.doSth();
		targetProxy2.doSth2();
	}
}

=========================
package testProxyInvocationHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class TargetInvocationHandler implements InvocationHandler {
	private Object target;

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public void beforeMethod() {
		System.out.println("before method");
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		beforeMethod();
		return method.invoke(target, args);
	}

}

===================
package testProxyInvocationHandler;

public class Target implements TargetInterface, TargetInterface2 {

	@Override
	public void doSth2() {
		System.out.println("Target dosomthing222222222");
	}

	@Override
	public void doSth() {
		System.out.println("Target dosomthing");
	}
}

=========================
package testProxyInvocationHandler;

public interface TargetInterface {
	void doSth();
}
======================
package testProxyInvocationHandler;

public interface TargetInterface2 {
	void doSth2();
}
=====================


运行结果:

设计模式之动态代理模式_第1张图片

你可能感兴趣的:(设计模式)