代理模式
代理模式(Proxy Pattern):是指为其他对象提供一种代理,以控制对这个对象的访问。
代理对象在客户端和目标对象之间起到中介作用,代理模式属于结构型设计模式。
使用代理模式主要有两个目的:
- 一是保护目标对象
- 二是增强目标对象
静态代理
package org.example.spring.designpattern.proxy.staticproxy;
/**
* @author ss_419
*/
public interface Person {
/**
* 人有很多行为,要谈恋爱,要住房子,要购物,要工作
*/
public void findLove();
}
package org.example.spring.designpattern.proxy.staticproxy;
/**
* TODO 儿子要找对象,实现Son类
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 10:46
*/
public class Son implements Person{
/**
*
*/
@Override
public void findLove() {
// 我没有时间,我要赚钱......
System.out.println("儿子要求:肤白貌美大长腿.....");
}
}
package org.example.spring.designpattern.proxy.staticproxy;
/**
* TODO 父亲要帮儿子相亲,实现Father类
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 10:54
*/
public class Father {
private Son son;
// 没办法扩展
public Father(Son son) {
this.son = son;
}
// 获取目标对象的引用
public void findLove(){
System.out.println("父亲物色对象");
this.son.findLove();
System.out.println("双方同意交往,确立关系...");
}
public static void main(String[] args) {
// 只能帮儿子找对象,不能帮表妹、不能帮陌生人
Father father = new Father(new Son());
father.findLove();
}
}
动态代理
动态代理和静态代理的基本思路是一致的,只不过动态代理功能更加强大,随着业务的扩展适应性更强。
JDK实现方式:
package org.example.spring.designpattern.proxy.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* TODO 创建媒婆(婚介所)
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 11:07
*/
public class JDKMeipo implements InvocationHandler {
// 被代理的对象,将引用保存下来
private Object target;
public Object getInstance(Object target) throws Exception {
this.target = target;
System.out.println("JDKMeipo is instance of "+target.getClass().getName());
Class<?> clazz = target.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object invoke = method.invoke(this.target, args);
after();
return invoke;
}
private void before(){
System.out.println("JDKMeipo before");
System.out.println("我是媒婆:我要给你找对象,现在已经确认你的需求");
System.out.println("..........开始物色..........");
}
private void after() {
System.out.println("如果合适的话,就准备办事?");
}
}
创建单身客户类Customer:
package org.example.spring.designpattern.proxy.dynamicproxy;
import org.example.spring.designpattern.proxy.staticproxy.Person;
/**
* TODO
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 11:57
*/
public class Customer implements Person {
@Override
public void findLove() {
System.out.println("找到了一个人的心");
System.out.println("高富帅");
System.out.println("18块腹肌");
}
}
创建测试:
package org.example.spring.designpattern.proxy.dynamicproxy;
import org.example.spring.designpattern.proxy.staticproxy.Person;
/**
* TODO
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 11:59
*/
public class DynamicProxyTest {
public static void main(String[] args) {
try {
Person obj = (Person) new JDKMeipo().getInstance(new Customer());
obj.findLove();
}catch (Exception e) {
e.printStackTrace();
}
}
}
手写实现JDK动态代理
不仅知其然,还得知其所以然。接下来我们自己动手写一个属于自己的动态代理
我们都知道JDK动态代理采用字节重组,重新生成对象来替代原始对象,以达到动态代理的目的。
JDK动态代理生成对象的步骤如下:
- 获取被代理对象的引用,并且获取它的所有接口,反射获取
- JDK动态代理类重新生成一个新的类,同时新的类要实现被代理实现的所有接口。
- 动态生成Java代码,新加的业务逻辑方法由一定的逻辑代码调用(在代码中体现)。
- 编译新生成的Java代码.class文件
- 重新加载到JVM中运行
以上的过程就叫字节码重组
JDK中有一个规范,在ClassPath下只要是$开头的.class文件,一般都是自动生成的。
第一步,创建Handler
package org.example.spring.designpattern.proxy.myproxy;
import java.lang.reflect.Method;
/**
* TODO 1、创建接口
* @author ss_419
*/
public interface GPInvocationHandler {
/**
* Invokes the method
* @return
*/
public Object invoke(Object proxy, Method method,Object[] args) throws Throwable;
}
第二步,用来生成源代码的工具类
package org.example.spring.designpattern.proxy.myproxy;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* TODO 2、用来生成源代码的工具类
*
* @author ss_419
* @version 1.0
* @date 2023/3/9 13:48
*/
public class GPProxy {
public static final String ln = "\r\n";
public static Object newProxyInstance(GPClassLoader classLoader, Class<?>[] interfaces, GPInvocationHandler h) {
try {
//1、动态生成源代码.java文件
String src = generateSrc(interfaces);
// System.out.println(src);
//2、Java文件输出磁盘
String filePath = GPProxy.class.getResource("").getPath();
// System.out.println(filePath);
File f = new File(filePath + "$Proxy0.java");
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//3、把生成的.java文件编译成.class文件
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manage = compiler.getStandardFileManager(null, null, null);
Iterable iterable = manage.getJavaFileObjects(f);
JavaCompiler.CompilationTask task = compiler.getTask(null, manage, null, null, null, iterable);
task.call();
manage.close();
//4、编译生成的.class文件加载到JVM中来
Class proxyClass = classLoader.findClass("$Proxy0");
Constructor c = proxyClass.getConstructor(GPInvocationHandler.class);
f.delete();
//5、返回字节码重组以后的新的代理对象
return c.newInstance(h);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String generateSrc(Class<?>[] interfaces) {
StringBuffer sb = new StringBuffer();
sb.append("package org.example.spring.designpattern.proxy.myproxy;" + ln);
sb.append("import org.example.spring.designpattern.proxy.staticproxy.Person;" + ln);
sb.append("import java.lang.reflect.*;" + ln);
sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{" + ln);
sb.append("GPInvocationHandler h;" + ln);
sb.append("public $Proxy0(GPInvocationHandler h) { " + ln);
sb.append("this.h = h;");
sb.append("}" + ln);
for (Method m : interfaces[0].getMethods()) {
Class<?>[] params = m.getParameterTypes();
StringBuffer paramNames = new StringBuffer();
StringBuffer paramValues = new StringBuffer();
StringBuffer paramClasses = new StringBuffer();
for (int i = 0; i < params.length; i++) {
Class clazz = params[i];
String type = clazz.getName();
String paramName = toLowerFirstCase(clazz.getSimpleName());
paramNames.append(type + " " + paramName);
paramValues.append(paramName);
paramClasses.append(clazz.getName() + ".class");
if (i > 0 && i < params.length - 1) {
paramNames.append(",");
paramClasses.append(",");
paramValues.append(",");
}
}
sb.append("public " + m.getReturnType().getName() + " " + m.getName() + "(" + paramNames.toString() + ") {" + ln);
sb.append("try{" + ln);
sb.append("Method m = " + interfaces[0].getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{" + paramClasses.toString() + "});" + ln);
sb.append((hasReturnValue(m.getReturnType()) ? "return " : "") + getCaseCode("this.h.invoke(this,m,new Object[]{" + paramValues + "})", m.getReturnType()) + ";" + ln);
sb.append("}catch(Error _ex) { }");
sb.append("catch(Throwable e){" + ln);
sb.append("throw new UndeclaredThrowableException(e);" + ln);
sb.append("}");
sb.append(getReturnEmptyCode(m.getReturnType()));
sb.append("}");
}
sb.append("}" + ln);
return sb.toString();
}
private static Map<Class, Class> mappings = new HashMap<Class, Class>();
static {
mappings.put(int.class, Integer.class);
}
private static String getReturnEmptyCode(Class<?> returnClass) {
if (mappings.containsKey(returnClass)) {
return "return 0;";
} else if (returnClass == void.class) {
return "";
} else {
return "return null;";
}
}
private static String getCaseCode(String code, Class<?> returnClass) {
if (mappings.containsKey(returnClass)) {
return "((" + mappings.get(returnClass).getName() + ")" + code + ")." + returnClass.getSimpleName() + "Value()";
}
return code;
}
private static boolean hasReturnValue(Class<?> clazz) {
return clazz != void.class;
}
private static String toLowerFirstCase(String src) {
char[] chars = src.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
}
第三步,创建 GPClassLoader 类:
package org.example.spring.designpattern.proxy.myproxy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
/**
* @author ss_419
*/
public class GPClassLoader extends ClassLoader {
private File classPathFile;
public GPClassLoader(){
String classPath = GPClassLoader.class.getResource("").getPath();
this.classPathFile = new File(classPath);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String className = GPClassLoader.class.getPackage().getName() + "." + name;
if(classPathFile != null){
File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");
if(classFile.exists()){
FileInputStream in = null;
ByteArrayOutputStream out = null;
try{
in = new FileInputStream(classFile);
out = new ByteArrayOutputStream();
byte [] buff = new byte[1024];
int len;
while ((len = in.read(buff)) != -1){
out.write(buff,0,len);
}
return defineClass(className,out.toByteArray(),0,out.size());
}catch (Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
第四步,创建 GPMeipo 类:
package org.example.spring.designpattern.proxy.myproxy;
import java.lang.reflect.Method;
/**
* @author ss_419
*/
public class GPMeipo implements GPInvocationHandler {
private Object target;
public Object getInstance(Object person) throws Exception{
this.target = person;
Class<?> clazz = target.getClass();
return GPProxy.newProxyInstance(new GPClassLoader(),clazz.getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object obj = method.invoke(this.target,args);
after();
return obj;
}
private void before(){
System.out.println("我是媒婆,我要给你找对象,现在已经确认你的需求");
System.out.println("开始物色");
}
private void after(){
System.out.println("OK的话,准备办事");
}
}
第五步,客户端测试代码:
package org.example.spring.designpattern.proxy.myproxy;
import org.example.spring.designpattern.proxy.dynamicproxy.Customer;
import org.example.spring.designpattern.proxy.staticproxy.Person;
public class GPProxyTest {
public static void main(String[] args) {
try {
//JDK动态代理的实现原理
Person obj = (Person) new GPMeipo().getInstance(new Customer());
System.out.println(obj.getClass());
obj.findLove();
}catch (Exception e){
e.printStackTrace();
}
}
}
标签:JDK,代理,public,new,import,设计模式,class,append,out
From: https://www.cnblogs.com/atwood-pan/p/17198447.html