为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
public interface Person { void giveMoney();// 交费 }
public class Student implements Person { private String name; public Student(String name) { this.name = name; } @Override public void giveMoney() { System.out.println(name + "上交班费100元"); } }
public class SquadLeader implements Person { private Student stu; public SquadLeader(Person stu) { if (stu instanceof Student) { this.stu = (Student) stu; } } @Override public void giveMoney() { System.out.println("班长收班费"); stu.giveMoney(); System.out.println("班长上交班费"); } }
public class StaticProxyTest { public static void main(String[] args) { Student zs = new Student("张三");// 创建学生(被代理)类 SquadLeader squadLeader = new SquadLeader(zs);// 创建班长(代理)类 squadLeader.giveMoney();// 班长代上交班费 } }
班长收班费 张三上交班费100元 班长上交班费
public interface Star { void sing(String name); void dance(String name); }
public class ChinaStar implements Star { private String name; public ChinaStar(String name) { this.name = name; } @Override public void sing(String name) { System.out.println(this.name + "唱了一首:" + name); } @Override public void dance(String name) { System.out.println(this.name + "跳了一段:" + name); } }
public class DynamicProxy<T> implements InvocationHandler { private T target; // 设置被代理的对象 public void setTarget(T target) { this.target = target; } // 创建代理对象 public T creatProxy() throws Exception { Objects.requireNonNull(target,"请先设置被代理对象"); return (T) Proxy.newProxyInstance(target.getClass(). getClassLoader(),target.getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object invoke = method.invoke(target, args); after(); return invoke; } private void before() { System.out.println("准备工作"); } private void after() { System.out.println("收尾工作"); } }
public class DynamicProxyTest { public static void main(String[] args) throws Throwable { // 三个被代理对象 ChinaStar liRongHao = new ChinaStar("李荣浩"); ChinaStar zhouJieLun = new ChinaStar("蔡徐坤"); Student zhangSan = new Student("张三"); // 一个动态代理类 DynamicProxy dynamicProxy = new DynamicProxy(); // 明星代理类 dynamicProxy.setTarget(liRongHao); Star star = (Star) dynamicProxy.creatProxy(); star.sing("年少有为"); System.out.println("******************************"); dynamicProxy.setTarget(zhouJieLun); star = (Star) dynamicProxy.creatProxy(); star.dance("鸡你太美"); System.out.println("******************************"); // 学生代理类 dynamicProxy.setTarget(zhangSan); Person person = (Person) dynamicProxy.creatProxy(); person.giveMoney(); } }
准备工作 李荣浩唱了一首:年少有为 收尾工作 ****************************** 准备工作 蔡徐坤跳了一段:鸡你太美 收尾工作 ****************************** 准备工作 张三上交班费100元 收尾工作