在上一篇静态代理模式的基础上改为动态代理模式
案例一
1.接口
//租房
public interface Rent {
public void rent();
}
2.真实角色
//房东
public class Host implements Rent {
public void rent(){
System.out.println("房东出租房子!");
}
}
3.自动生成代理类的类
InvocationHandler会自动生成代理类,创建一个类实现这个类
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 {
//动态代理的本质,就是使用反射机制实现!
seeHouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse() {
System.out.println("中介带看房子");
}
public void fare() {
System.out.println("收取中介费");
}
}
4.客户访问
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就是动态生成的,我们并没有写
proxy.rent();
}
}
案例二
1.接口
public interface UserService{
void add();
void delete();
void update();
void query();
}
2.真实角色
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void query() {
System.out.println("查询了一个用户");
}
}
3.自动生成代理类的类
//等我们会用这个类, 自动生成代理类!
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 + "方法");
}
}
4.客户访问
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.query();
}
}
总结
动态代理的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可