标签:实现 http 租赁合同 service 字节 this 角色 asc 模式
为什么要学习代理模式? 因为这就是SpringAOP的底层
代理模式的分类:

角色分析:
接口:
public interface Rent {
    public void rent();
}真实角色
public class Host implements Rent {
    public void rent() {
        System.out.println("包租婆出租屋");
    \}
}代理角色
public class Proxy implements Rent {
    private Host host;
    public Proxy() {
    }
    public Proxy(Host host) {
        this.host = host;
    }
    public void rent() {
        System.out.println("通过代理:");
        see();
        host.rent();
        sign();
        fee();
    }
    public void see(){
        System.out.println("中介带你看房");
    }
    public void sign(){
        System.out.println("签租赁合同");
    }
    public void fee(){
        System.out.println("收中介费");
    }
}客户
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}代理模式的好处:
缺点:
需要了解两个类: Proxy(代理) , InvocationHandler(调用处理程序)
动态代理的使用
public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Object target;
    public void setTarget(Object target) {
        this.target = target;
    }
    //生产得到代理类
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }
    //处理代理实例并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //动态代理的本质,就是使用反射机制
        Object result = method.invoke(target, args);
        return null;
    }
    public void log(String msg){
        System.out.println("执行力"+msg+"方法");
    }
}
public class Client {
    public static void main(String[] args) {
        UserServiceImpl service = new UserServiceImpl();
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setTarget(service);
        UserService proxy = (UserService) proxyInvocationHandler.getProxy();
        proxy.add();
        proxy.update();
        proxy.query();
        proxy.delete();
    }
}
好处:
标签:实现 http 租赁合同 service 字节 this 角色 asc 模式
原文地址:https://www.cnblogs.com/pinked/p/12198789.html