静态代理要搞清楚三个关系:客户类 代理类 委托类
代理类的行为要类似且强于委托类(实现方法有1.继承,2.代理类与委托类实现共同的接口(首选))
/**
* 用静态代理模式完成日志的操作
* @author Administrator
*
*/
public class UserAction {
private UserDao userDao = UserDaoFac.newUserDao();
public void add(){
System.out.println("========UserAction========");
userDao.add();
}
public static void main(String[] args) {
new UserAction().add();
}
}
public interface UserDao { //接口
public void add();
}
public class UserDaoImpl implements UserDao{ 委托类
@Override
public void add() {
System.out.println("=====UserDao======");
// System.out.println("完成日志操作!!!");//侵入式 植入式代码
}
}
public class UserDaoFac { //工厂
public static UserDao newUserDao(){
return new UserPowerProxy(new UserLogProxy(new UserDaoImpl()));
}
}
public class UserLogProxy implements UserDao { //代理类
private UserDao userDao;
//构造注入
public UserLogProxy(UserDao userDao) {
super();
this.userDao = userDao;
}
@Override
public void add() {
userDao.add();//把委托类的活干了
System.out.println("添加了日志操作");
}
}
public class UserPowerProxy implements UserDao { //代理类
private UserDao userDao;
//构造注入
public UserPowerProxy(UserDao userDao) {
super();
this.userDao = userDao;
}
@Override
public void add() {
System.out.println("增加一个权限判断");
userDao.add();
}
}