一、静态代理
使用静态代理,要创建三个步骤:
- 定义抽象角色
- 定义具体角色
- 定义代理角色
public interface Star { // 定义抽象角色 void singing();}
public class Eason implements Star { @Override public void singing() { System.out.println("我是陈奕迅,我唱淘汰"); }}
public class EasonProxy implements Star { public EasonProxy(Star star) { this.star = star; } private Star star; @Override public void singing() { System.out.println("我是经纪人,我代理陈奕迅"); star.singing(); System.out.println("胖子唱完歌了"); }}
二、动态代理
动态代理在spring aop上有使用到。
1)jdk动态代理
public interface Star { // 定义抽象角色 void singing();}
public class Eason implements Star { @Override public void singing() { System.out.println("我是陈奕迅,我唱淘汰"); }}
public class StarHandler implements InvocationHandler { private Star realStar; public StarHandler(Star realStar) { super(); this.realStar = realStar; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = null; System.out.println("我被代理之前干的事情"); object = method.invoke(realStar, args); System.out.println("我被代理之后干的事情"); return object; }}
public static void main(String[] args) { Star star = new Eason(); StarHandler handler = new StarHandler(star); Star proxy = (Star) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Star.class}, handler); proxy.singing();}