* 代理必须持有被代理的对象,而且还必须跟被代理对象实现相同的接口
* 不管是静态代理还是动态代理都必须满足以上2个规则
代理的作用:
能够在不改变原来代码的逻辑的情况下增加代码功能
基于以上2个原则,所以代理和非代理才能达到相同的目的
1.静态代理 静态代理只能代理一个对象,
优点:代码逻辑清晰简单
例如下面就只能代理Star
public class StaticProxy implements Star{
private Star star;
public Star getStar() {
return star;
}
public void setStar(Star star) {
this.star = star;
}
@Override
public String sing(String musicName) {
//增强
System.out.println("增强开始");
String result= star.sing(musicName);
System.out.println("增强结束");
//增强结束
return result;
}
@Override
public String dance(String danceName) {
//增强
System.out.println("增强开始");
String result= star.dance(danceName);
System.out.println("增强结束");
//增强结束
return result;
}
}
2.动态代理,可以代理各种对象,必须要实现implements InvocationHandler
缺点:代码逻辑稍微绕了点
public class MyProxy implements InvocationHandler {
// 目标类,也就是被代理对象
private Object target;
public void setTarget(Object target) {
this.target = target;
}
/**
* 可以做增强
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("收钱");
Object result = method.invoke(target, args);//调用代理
return result;
}
}
动态 代理工具类
public class ProxyUtil {
public static Object CreatProxyedObj(Object target,InvocationHandler h)
{
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), h);
}
}
测试类
public class TestProxy {
public static void main(String[] args) {
Star ldh = new HongKongStar();
MyProxy starProxy = new MyProxy();
starProxy.setTarget(ldh);
Star proxy = (Star) ProxyUtil.CreatProxyedObj(ldh, starProxy);
proxy.sing("今天");
proxy.dance("开心的马六");
CrmDao dao = new CrmDaoImpl();
MyProxy daoProxy = new MyProxy();
daoProxy.setTarget(dao);
CrmDao crmDao =(CrmDao) ProxyUtil.CreatProxyedObj(dao, daoProxy);
crmDao.delete(1);
crmDao.queryById(1);
crmDao.update(1);
}
}
public interface Star {
public String sing(String musicName);
public String dance(String danceName);
}
package com.asiainfo.zy;
public class HongKongStar implements Star{
@Override
public String sing(String musicName) {
System.out.println("准备开始唱"+musicName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("唱歌结束");
return musicName;
}
@Override
public String dance(String danceName) {
System.out.println("音乐响起,准备开始跳舞"+danceName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("跳舞结束");
return danceName;
}
}