代理模式
静态代理 (实现与目标对象同样的接口)
//app
@Test
public void test(){
BuyHourse buyHourse = new BuyHourseImpl();
BuyHourse buyhourseprofxy = new BuyHourseProfxy(buyHourse);
buyhourseprofxy.byHourse();
}
//接口
public interface BuyHourse {
public void byHourse();
}
//实现类
public class BuyHourseImpl implements BuyHourse{
@Override
public void byHourse() {
// TODO Auto-generated method stub
System.out.println("买房");
}
}
//代理类
public class BuyHourseProfxy implements BuyHourse {
private BuyHourse target;
public BuyHourseProfxy(BuyHourse target){
this.target = target;
}
@Override
public void byHourse() {
System.out.println("买房前准备");
target.byHourse();
System.out.println("买房后的准备");
}
}
动态代理(目标对象必须实现接口)
//appp
public void test(){
BuyHourse buyHourse = new BuyHourseImpl();
BuyHourse obj = (BuyHourse)new ProfxyFactory(buyHourse).getProfxyInstance();
obj.byHourse();
}
public class ProfxyFactory {
//维护一个目标对象
private Object target;
public ProfxyFactory(Object target){
this.target = target;
}
//给目标对象生成代理对象
public Object getProfxyInstance(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("买房前准备");
//目标对象
Object returnValue = method.invoke(target, args);
System.out.println("买房后的准备");
System.out.println(returnValue);
return returnValue;
}
});
}
}
动态代理(静态方法)
省略构造函数,直接在方法里面传入参数,
cblib代理(不需要目标对象实现接口)
//app
public void test(){
BuyHourse buy = new BuyHourse();
BuyHourse proxy = (BuyHourse) new ProfxyFactory(buy).getProxyInstance();
proxy.byHourse();
}
//代理类
public class ProfxyFactory implements MethodInterceptor{
//维护一个目标对象
private Object target;
public ProfxyFactory(Object target){
this.target = target;
}
//给目标对象创建代理对象
public Object getProxyInstance(){
//工具类
Enhancer en= new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("买房准备");
//执行目标对象方法
Object returnValue = method.invoke(target, args);
System.out.println("买房后---");
return returnValue;
}
}