设计模式10——动态代理模式
代码实现:
package com.ghl.dynammicproxy;
/**
* @ProjectName DesignPattern
* @ClassName Rent
* @Date 2020/8/29 20:57
* @Author gaohengli
* @Version 1.0
*/
//动态代理模式
//租房
public interface Rent {
public void rent();
}
package com.ghl.dynammicproxy;
/**
* @ProjectName DesignPattern
* @ClassName Host
* @Date 2020/8/29 20:58
* @Author gaohengli
* @Version 1.0
*/
//房东
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
package com.ghl.dynammicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @ProjectName DesignPattern
* @ClassName ProxyInvocationHandler
* @Date 2020/8/29 21:45
* @Author gaohengli
* @Version 1.0
*/
//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler{
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到的代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回运行结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现
seeHose();
Object result = method.invoke(rent, args);
heotong();
return result;
}
private void seeHose(){
System.out.println("中介带你看房子");
}
private void heotong(){
System.out.println("中介带你签合同");
}
}
package com.ghl.dynammicproxy;
/**
* @ProjectName DesignPattern
* @ClassName Client
* @Date 2020/8/29 22:03
* @Author gaohengli
* @Version 1.0
*/
//客户端租房
public class Client {
public static void main(String[] args) {
//真实对象
Host host = new Host();
//代理角色:现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
//动态生成代理类
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}