目录
代理
java的代理都是基于接口实现的,代理使得原本不具有某种行为的类在不修改源码的情况下具有某种行为能力。
静态代理:只能代理某一类型的接口的实例。不能做到任何类任何方法的代理。
不使用代理案例
/**
一些公共操作的逻辑都需要自己在每个方法里单独写一遍
*/
//接口
public interface MapperInterface {
void save(User user);
}
//实现类1
public class StudentMapper implements MapperInterface{
@Override
public void save(User user) {
System.out.println("建立连接");
System.out.println("保存student");
System.out.println("提交事务");
System.out.println("断开连接");
}
}
//实现类2
public class UserMapper implements MapperInterface {
@Override
public void save(User user) {
System.out.println("建立连接");
System.out.println("保存user");
System.out.println("提交事务");
System.out.println("断开连接");
}
}
静态代理案例
/**
上面的案例: 实现同一个接口的类有好多公共的代码每次都写一遍很麻烦又没有技术含量。
这样的公共的事情可以让代理去实现。本类只需要写核心代码即可
*/
//实现类1
public class StudentMapper implements MapperInterface {
@Override
public void save(User user) {
System.out.println("保存student");
}
}
//实现类2
public class UserMapper implements MapperInterface {
@Override
public void save(User user) {
System.out.println("保存user");
}
}
/**静态代理类(把公共的处理逻辑放在代理里面,代理通过构造方法传入被代理的对象(从而掌握了它),
可以随时调用其中的方法),就可以在其前其后做一些公共的逻辑
*/
public class StaticProxy {
MapperInterface mapperInterface;
public StaticProxy(MapperInterface mapperInterface) {
this.mapperInterface = mapperInterface;
}
public String save(User user) {
System.out.println("建立连接");
this.mapperInterface.save(user);
System.out.println("提交事务");
System.out.println("断开连接");
return user.getUserName();
}
}
//测试
public class TestStaticProxy {
@Test
public void test() {
StaticProxy staticProxy = new StaticProxy(new UserMapper());
staticProxy.save(new User());
}
}
测试结果: