动态代理

动态代理

抽象角色

public interface Rent {
    public void rent();
}

真实角色

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

代理角色

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 );
    }

    //proxy: 代理类
    //method : 代理类的调用处理程序的方法对象
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(target, args);
        return result;
    }
}

测试类

public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setTarget(host);
        Rent proxy = (Rent) proxyInvocationHandler.getProxy();
        proxy. rent();
    }
}
posted @ 2023-04-02 17:42  KxWanna  阅读(22)  评论(0)    收藏  举报