代理模式在Spring中,运用的淋漓精致,面向切面的编程,变得很有趣
假设有个实际书籍供应商,网上书籍供应商,而网上书籍供应商是代理商
package com.study.proxy;
public interface Subject {
public void sailBook();
}
package com.study.proxy;
//真实卖家,最初卖家
public class RealSubject implements Subject {
@Override
public void sailBook() {
System.out.println("卖书");
}
}
网上代理商代理类:
package com.study.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Date;
//代理商
public class MyHandler implements InvocationHandler {
private Object realSub = null;
public void setSub(Object sub){
this.realSub = sub;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(this.realSub==null){
System.out.println("你无权操作");//判断权限
return null;
}else{
String dazhe = DaZhe();
System.out.println(dazhe);
Object rtObj = method.invoke(realSub, args);
String give = Give();
System.out.println(give);
String log = dazhe+give+new Date();
System.out.println(log);
return rtObj;
}
}
private String DaZhe(){
return "打折信息";
}
private String Give(){
return "送代金券";
}
}
客户端,测试类
package com.study.proxy;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) {
Subject sub = new RealSubject();
MyHandler handler1 = new MyHandler();
MyHandler handler2 = new MyHandler();
handler1.setSub(sub);
Subject proxySub1 = (Subject) Proxy.newProxyInstance(
RealSubject.class.getClassLoader(),
RealSubject.class.getInterfaces(), handler1);
Subject proxySub2 = (Subject) Proxy.newProxyInstance(
RealSubject.class.getClassLoader(),
RealSubject.class.getInterfaces(), handler2);
proxySub1.sailBook();
proxySub2.sailBook();
}
}