this.mSource = source;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(!checkLogin()){
jumpToLoginActivity();
return null;
}
return method.invoke(mSource, args);
}
private boolean checkLogin(){
System.out.println(“用户未登录”);
return false;
}
private void jumpToLoginActivity(){
System.out.println(“跳转到登录页”);
}
}
public class Client {
public static void main(String[] args) {
IUserSetting source = new UserSetting();
IUserSetting iUserSetting = LoginCheckHandler.proxy(source,IUserSetting.class);
iUserSetting.changePwd(“new Password”);
}
}
经过这样封装之后,检查登录跳转登录页的逻辑作为横切关注点就和业务主体进行了分离。当有新的需求需要登录检查时,我们只需要通过LoginCheckHandler生成新的代理对象即可。