interface Eat{ void eat() ; } class RealEat implements Eat{ public void eat(){ System.out.println("###真实主题的核心操作###"); } } class EatProxy implements InvocationHandler{ private Eat eat ; public Eat bind(Eat eat){ this.eat = eat ; return (Eat)Proxy.newProxyInstance(eat.getClass().getClassLoader(), eat.getClass().getInterfaces(), this); } public Object invoke(Object obj,Method method,Object[] args) throws Throwable{ this.prepare(); Object obj1 = method.invoke(this.eat, args); this.finish(); return obj1 ; } private void prepare(){ System.out.println("代理的准备工作"); } private void finish(){ System.out.println("代理的收尾工作"); } } public class Test{ public static void main(String[] args){ EatProxy proxy = new EatProxy() ; Eat eat = proxy.bind(new RealEat()) ; eat.eat(); } }
运行结果:
代理的准备工作
###真实主题的核心操作###
代理的收尾工作