代理设计模式:通过代理完成目标对象的工作,同时代理还可以做自己的事情。
代理设计模式根据代理对象的生成时机分为两类:
A:静态代理:代理类在程序运行前已经存在了。
B:动态代理:代理类在程序运行过程中通过反射技术自动生成的,在程序运行之前是看到静态代理类的。
代理设计模式的实现方式:
A:如果目标类已经实现了某个接口,则代理类和目标类实现相同的接口并在代理类中持有目标类的引用,
JDK动态代理使用的就是这种方式。
B:如果目标类没有实现任何接口则生成代理类是目标类的子类,此时目标类一定不能是final类。
(静态代理)实现接口的例子:
public interface PersonDao {
void add(String name);
}
public class PersonDaoBean implements PersonDao {
@Override
public void add(String name) {
System.out.println(name+"完成添加Person对象的工作");
}
}
public class PersonDaoProxyBean implements PersonDao {
private PersonDao personDao;
public PersonDaoProxyBean(PersonDao personDao){
this.personDao=personDao;
}
@Override
public void add(String name) {
this.validate();
//调用目标类中的方法
this.personDao.add(name);
this.log();
}
private void log() {
System.out.println("增加添加日志的工作");
}
private void validate() {
System.out.println("数据校验工作!");
}
}
测试类
public class TestPersonDaoDemo01 {
public static void main(String[] args) {
/*PersonDao personDao=new PersonDaoBean();
personDao.add("张三");*/
//目标对象
PersonDao personDao=new PersonDaoBean();
//在实例化代理对象是将目标对象作为参数传递到了代理对象中
PersonDao personDaoProxy=new PersonDaoProxyBean(personDao);
personDaoProxy.add("夏利");
}
}
(动态代理)实现接口的例子:
public interface PersonDao {
void add(String name);
int minus(int a,int b);
}
public class PersonDaoBean implements PersonDao {
@Override
public void add(String name) {
System.out.println(name+"完成添加Person对象的工作");
}
@Override
public int minus(int a, int b) {
int result=a-b;
System.out.println("==PersonDaoBean.minus(int a="+a+", int b="+b+")===");
return result;
}
}
代理工厂
public class ProxyFactory {
private Object target;
public ProxyFactory(Object target) {
this.target = target;
}
public Object getProxyIntances() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始");
Object result = method.invoke(target, args);
System.out.println("结束");
return result;
}
});
}
}
测试类
public class TestStaticAgent {
public static void main(String[] args) throws Exception {
PersonDao target=new PersonDaoBean();
PersonDao proxy=(PersonDao) new ProxyFactory(target).getProxyIntances();
Person person=new Person("KK", 15, "ni", new Date());
proxy.add(person);
int result=proxy.minus(5, 2);
System.out.println(result);
}
}