Spring--->代理模式

1、代理模式()

  • 抽象角色:共同的任务,都要去做的事
  • 真实角色:被代理的角色
  • 代理角色:代理真实的对象并做附属操作
  • 客户:访问代理对象的人
  1. 接口
    public interface Rent {
        public void rent();
    }
  2. 真实角色
    public class House implements Rent {
        public void rent() {
            System.out.println("房东出租房子");
        }
    }
  3. 代理角色
    public class Proxy implements Rent {
        private House house;
        public Proxy() {
        }
        public Proxy(House house) {
            this.house = house;
        }
        public void rent() {
            //house.rent();
            System.out.println("中介出租房子");
            hetong();
            fare();
        }
        public void fare(){
            System.out.println("收费");
        }
        public void hetong(){
            System.out.println("签合同");
        }
    }
  4. 客户访问代理角色
    @org.junit.Test
        public void test02(){
            House house=new House();
            Proxy proxy=new Proxy(house);
            proxy.rent();
        }

好处,优点:

  • 可以使真实角色的操作更加纯粹!不去关注公共的业务

  • 公共交给代理角色,实现业务的分工

  • 公共业务发生拓展时,方便集中管理

缺点:

  • 一个真实对象就需要一个代理角色,代码翻倍

2、动态代理【重点】

1、代理工具类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class InvocationHandlerProxy 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 {
        //实现接口里的 对应方法,方法名通过传递args进来
        Object result = method.invoke(target, args);
        return result;
    }
}

2、实际操作

public class Client {
    public static void main(String[] args) {
        //真实角色
        House house=new House();
        InvocationHandlerProxy pih = new InvocationHandlerProxy();
        //传入要获取的对象
        pih.setTarget(house);
        //获取代理对象
        Rent rent = (Rent) pih.getProxy();
        rent.rent();

    }
}
原文地址:https://www.cnblogs.com/springxian/p/13658470.html