一、自己理解
所谓静态代理,其实就是代理类由自己实现,编译时期.class文件已经存在。代理类和委托类(被代理类),实现相同接口,在委托类中实现具体的业务逻辑,而代理类这做数据预处理等工作
二、代码实现
User.java文件
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private String username;
private String password;
}
IUserDao.java文件
public interface IUserDao {
void saveUser(User user);
int updateUser(User user);
}
UserDaoImpl.java文件
public class UserDaoImpl implements IUserDao {
@Override
public void saveUser(User user) {
System.out.println("UserDaoImpl save user.");
}
@Override
public int updateUser(User user) {
System.out.println("UserDaoImpl update user.");
return 0;
}
}
UserStaticProxy.java文件
public class UserStaticProxy implements IUserDao {
private IUserDao userDao = null;
public UserStaticProxy(IUserDao userDao) {
this.userDao = userDao;
}
@Override
public void saveUser(User user) {
System.out.println("Proxy saveUser before.");
userDao.saveUser(user);
System.out.println("Proxy saveUser after.");
}
@Override
public int updateUser(User user) {
System.out.println("Proxy updateUser before.");
int affectRecords = userDao.updateUser(user);
System.out.println("Proxy updateUser after.");
return affectRecords;
}
}
三、测试
public class UserProxyTest {
@Test
public void testStaticProxy() {
User user = new User();
IUserDao userDao = new UserDaoImpl();
IUserDao proxyUserDao = new UserStaticProxy(userDao);
proxyUserDao.saveUser(user);
proxyUserDao.updateUser(user);
}
}