java语言通过java.lang.reflect苦,提供了三个类直接支持代理模式:Proxy,InvocoationHandler,Method三个类。
Prxoy能在运行时间创建代理对象,当系统有一个代理对象后,对源对象的方法调用会首先被分派给一个调用处理器(InvocationHandler接口),InvocationHandler接口中有一个invoke()方法,程序可以在调用处理器的invoke()方法中截获这个调用,进行额外的操作。
- public interface SaleComputer {
- public void sale(String type);
- }
- public class ComputerMaker implements SaleComputer {
- public void sale(String type) {
- System.out.println("卖出了一台"+type+"电脑");
- }
- }
- public class ComputerProxy {
- public static SaleComputer getComputerMaker(){
- ProxyFunction pf=new ProxyFunction();
- return (SaleComputer)Proxy.newProxyInstance(ComputerMaker.class.getClassLoader(), ComputerMaker.class.getInterfaces(), pf);
- }
- }
- public class ProxyFunction implements InvocationHandler {
- private ComputerMaker cm;
- public void youHui(){
- System.out.println("我给你一些优惠。。。");
- }
- public void giveMouse(){
- System.out.println("我还要送你一个鼠标。。。 ");
- }
- public Object invoke(Object arg0, Method arg1, Object[] arg2)
- throws Throwable {
- String type=(String)arg2[0];
- if(type.equals("联想")||type.equals("三星")){
- if(cm==null){
- cm=new ComputerMaker();
- youHui();
- giveMouse();
- arg1.invoke(cm, type);
- }
- }else{
- System.out.println("我没有你要的这个牌子的电脑。。。。");
- }
- return null;
- }
- }
- public class Test {
- public static void main(String[] args) {
- SaleComputer sc=ComputerProxy.getComputerMaker();
- //sc.sale("联想");
- //sc.sale("三星");
- sc.sale("Dell");
- }
- }