静态代理
代理接口
public interface Person {public String wakeUp(String name);public String lunch(String name);
}
被代理对象
public class Student implements Person{@Overridepublic String wakeUp(String name) {System.out.println(name+"星期一早上8点上班!");return name+"wakeup";}@Overridepublic String lunch(String name) {System.out.println(name+"中午和某某一起在国际饭店吃午饭");return name+"lunch";}
}
静态代理对象
public class proxyStudent implements Person{public Student student=new Student();@Overridepublic String wakeUp(String name) {System.out.println(name+"的妈妈已经做好了早餐,准备叫她起床~");return student.wakeUp(name);}@Overridepublic String lunch(String name) {System.out.println(name+"的同事已经下班,正在等待她下班,一起去吃午饭~");return student.lunch(name);}
}
测试
public class proxyStudentTest {public proxyStudent proxyStudent=new proxyStudent();@Testpublic void wakeUp() {proxyStudent.wakeUp("莹莹");}@Testpublic void lunch() {proxyStudent.lunch("莹莹");}
}
动态代理
代理接口person 类
被代理对象 student 类
jdk动态代理,使用jdk动态代理让程序在运行的过程中动态的帮我们去创建代理对象这个类,然后创建对象
public class proxyUtile2 {private Person person=new Student();public Person createProxy(){Object o = Proxy.newProxyInstance(proxyUtile2.class.getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println(method.getName());if (method.getName().equals("lunch")){System.out.println(Arrays.toString(args)+"的同事已经下班,正在等待她下班,一起去吃午饭~");method.invoke(person,args);}else if(method.getName().equals("wakeUp")){System.out.println(Arrays.toString(args)+"的妈妈已经做好了早餐,准备叫她起床~");method.invoke(person,args);}else {System.out.println("没有此功能~");}return null;}});return (Person)o;}
}
测试
public proxyUtile2 proxyUtile2=new proxyUtile2();@Testpublic void createProxy() {Person proxy = proxyUtile.createProxy();proxy.lunch("青禾");proxy.wakeUp("青禾");Person proxy2 = proxyUtile2.createProxy();proxy2.lunch("青禾er");proxy2.wakeUp("青禾er");}