代理模式定义

代理模式 是指为其他对象提供一种代理,以控制对这个对象的访问

静态代理模式

demo:大部分的房主会把房子交给中介去出租,那么这个场景就是房主是真实类,中介是代理类(帮助房主出租房子),直接上代码

顶层接口

public interface IBuyHouse {

void renting();  

}

房主

public class Homeowner implements IBuyHouse {  
    @Override  
 public void renting() {  
        System.out.println("customer: i want to buy house");  
 }  
}

中介

public class IntermediaryProxy implements IBuyHouse {  
  
    private IBuyHouse iBuyHouse;  
  
 public IntermediaryProxy(IBuyHouse iBuyHouse) {  
        this.iBuyHouse = iBuyHouse;  
 }  
  
    @Override  
 public void renting() {  
        before();  
        iBuyHouse.renting();  
        after();  
 }  
  
    private void before() {  
        System.out.println("中介和客户沟通 ,要找一个什么样的房子");  
  
 }  
    private void after() {  
        System.out.println("达成协议,交定金");  
 }  
}

测试

public static void main(String[] args) {  
    IBuyHouse iBuyHouse = new IntermediaryProxy(new Homeowner());  
 iBuyHouse.renting();  
}

这样就完成了一个代理类的调用
接下来我们,我们看看如何实现动态代理

动态代理(java)

中介(代理类)

public class IntermediaryProxy implements InvocationHandler {  
  
    private IBuyHouse target;  
 public IBuyHouse instance(IBuyHouse target){  
        this.target = target;  
 Class<? extends IBuyHouse> aClass = target.getClass();  
 return (IBuyHouse) Proxy.newProxyInstance(aClass.getClassLoader(), aClass.getInterfaces(), this);  
 }  
  
    @Override  
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
        before();  
 Object invoke = method.invoke(this.target, args);  
 after();  
 return invoke;  
 }  
  
    private void before() {  
        System.out.println("中介和客户沟通 ,要找一个什么样的房子");  
  
 }  
  
    private void after() {  
        System.out.println("达成协议,交定金");  
 }  
  
}
// 调用
public static void main(String[] args) {  
    IBuyHouse instance = new IntermediaryProxy().instance(new Homeowner());  
 instance.renting();  
}

通过Proxy.newProxyInstance(...)创建一个代理类,然后调用重写的invoke方法去实现逻辑。
以上是jdk提供的一种方法,接下来我们用Cglib实现一下

cglib实现动态代理

public class IntermediaryProxy implements MethodInterceptor {  
  
    public Object instance(Class<?> clazz){  
        Enhancer enhancer = new Enhancer();  
 enhancer.setSuperclass(clazz);  
 enhancer.setCallback(this);  
 return enhancer.create();  
 }  
  
    @Override  
 public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {  
        before();  
 methodProxy.invokeSuper(o, objects);  
 after();  
 return null; }  
  
    private void before() {  
        System.out.println("中介和客户沟通 ,要找一个什么样的房子");  
  
 }  
  
    private void after() {  
        System.out.println("达成协议,交定金");  
 }  
  
}
// 调用
public static void main(String[] args) {  
    Homeowner homeowner = (Homeowner) new IntermediaryProxy().instance(Homeowner.class);  
 homeowner.renting();  
 homeowner.getMoney();  
}

用cglib实现动态代理是不需要通过接口的 也就是之前的IBuyHouse 是不需要创建的,cglib代理类是直接继承真实类去实现代理的。


大云梦
10 声望0 粉丝