Spring_代理模式

静态代理

比如,现在有房东,租客。房东想要出租房,租客想要租房,但在现实中,房东不好去找租客,租客也不好去找房东。那怎么办呢,就出现了中介,中介帮助房东代理去
出租房,那租客也方便了,想租房就直接去中介公司就行。中介公司就算是一个代理对象。

public interface Rent {

    public void rent();
}

//房东
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

public class Proxy implements Rent{

    private Host host;

    public Proxy(){
    }
    public Proxy(Host host){
        this.host=host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        free();
    }
    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    //签合同
    public void hetong(){
        System.out.println("签合同");
    }

    //收中介费
    public void free(){
        System.out.println("收中介费");
    }
}

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host =new Host();
        //代理,中介都帮房东租房子,但是,中介还会做一些附属操作
        Proxy proxy = new Proxy(host);
        //你不用面对房东,直接找中介租房就可
        proxy.rent();
    }
}

动态代理

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

//用这个类,自动生成代理类
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);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        //动态代理的本质,是反射
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }

import com.fan.demo1.UserService;
import com.fan.demo1.UserServiceImpl;

public class Client {
    public static void main(String[] args) {
//        真实角色
        UserServiceImpl userService = new UserServiceImpl();
//        代理角色,不存在
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
//        设置要代理的对象
        pih.setTarget(userService);
//        动态生成代理类
        UserService proxy = (UserService) pih.getProxy();

        proxy.add();
    }
}
posted @ 2023-01-06 13:38  Fannaa  阅读(13)  评论(0)    收藏  举报