/** * 被代理类(猫) */ public class Cat implements Action{ @Override public void eat(){ System.out.println("猫吃饭了!"); } }
/** * 静态代理需要自己写代理类-->代理类需要实现与目标对象相同的接口 */ public interface Action { //吃饭的动作 void eat(); }
/** * 代理类(铲屎官) --- 静态代理 */ public class ProxyDemo implements Action{ private Cat cat; public ProxyDemo(Cat cat){ this.cat = cat; } //透明代理 public ProxyDemo(){ this.cat = new Cat(); } public void clear(){ System.out.println("猫吃完了,要给它铲屎!"); } @Override public void eat(){ cat.eat(); clear(); } public static void main(String[] args) { //吃饭的猫 Cat cat = new Cat(); //受委托的猫 ProxyDemo proxyDemo = new ProxyDemo(cat); //猫让代理类(铲屎官)来铲屎 proxyDemo.eat(); //透明代理 ProxyDemo proxyDemo1 = new ProxyDemo(); proxyDemo.eat(); } }
动态代理:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 动态代理 */ public class DynamicProxy implements InvocationHandler { private Object object; public DynamicProxy(Object object){ this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before invoke " + method.getName()); method.invoke(object, args); System.out.println("After invoke " + method.getName()); return null; } public static void main(String[] args1) { //saveGeneratedFiles:是否保存生成的代理类class文件,默认false不保存 System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); Action action = new Cat(); InvocationHandler handler = new DynamicProxy(action); Action proxyCat = (Action) Proxy.newProxyInstance(action.getClass().getClassLoader(), action.getClass().getInterfaces(), handler); //猫吃饭前后插入两个输出日志 proxyCat.eat(); } }