定义与模型
‘
应用场景和分类
代码实现
staticProxy
public interface Star { /** * 面谈 */ void confer(); /** * 签合同 */ void signContract(); /** * 订票 */ void bookTicket(); /** * 唱歌 */ void sing(); /** * 收钱 */ void collectMoney(); }
public class RealStar implements Star{ @Override public void confer() { System.out.println("真实角色面谈"); } @Override public void signContract() { System.out.println("真实角色签合同"); } @Override public void bookTicket() { System.out.println("真实角色订票"); } @Override public void sing() { System.out.println("真实角色唱歌"); } @Override public void collectMoney() { System.out.println("真实角色收钱"); } }
public class ProxyStar implements Star{ private Star star; public ProxyStar(Star star) { super(); this.star = star; } @Override public void confer() { System.out.println("代理角色面谈"); } @Override public void signContract() { System.out.println("代理角色签合同"); } @Override public void bookTicket() { System.out.println("代理角色订票"); } @Override public void sing() { star.sing(); //代理角色不能唱歌 } @Override public void collectMoney() { System.out.println("代理角色收钱"); } }
public class Client { public static void main(String[] args) { Star real = new RealStar(); Star proxy = new ProxyStar(real); proxy.confer(); proxy.signContract(); proxy.bookTicket(); proxy.sing(); proxy.collectMoney(); } }
dynamicProxy
public interface Star { /** * 面谈 */ void confer(); /** * 签合同 */ void signContract(); /** * 订票 */ void bookTicket(); /** * 唱歌 */ void sing(); /** * 收钱 */ void collectMoney(); }
public class RealStar implements Star{ @Override public void confer() { System.out.println("真实角色面谈"); } @Override public void signContract() { System.out.println("真实角色签合同"); } @Override public void bookTicket() { System.out.println("真实角色订票"); } @Override public void sing() { System.out.println("真实角色唱歌"); } @Override public void collectMoney() { System.out.println("真实角色收钱"); } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class StarHandler implements InvocationHandler{ Star realStar; public StarHandler(Star realStar) { super(); this.realStar = realStar; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //System.out.println("****查看调用过程*****"); //Client调用的时候经过这里 Object object = null; System.out.println("真正的方法执行前,面谈,签合同,订票"); if(method.getName().equals("sing")){ object = method.invoke(realStar, args); } System.out.println("真正的方法执行后,收钱"); return object; } }
public class Client { public static void main(String[] args) { Star realStar = new RealStar(); StarHandler handler = new StarHandler(realStar); Star proxy = (Star) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Star.class}, handler); proxy.bookTicket(); proxy.sing(); } }
推荐博客
http://blog.csdn.net/rock_ray/article/details/22491763