适配器模式UML类图:
Adaptee角色:被适配角色 (UserService)
Adapter角色:适配器角色(LoginAdapter)
Target角色:目标角色(Login3rdTarget)
一、被适配角色
import java.util.*;
public class UserService {
public String login(String account, String password) {
return "Register Success!";
}
public boolean checkUserExists(String userName) {
return true;
}
public Object createTicket(String type, String userId, String content, String title) {
return null;
}
}
二、适配器角色
@Component
public class LoginAdapter extends UserService implements LoginTarget{
@Value("${gitee.state}")
private String giteeState;
@Value("${gitee.token.url}")
private String giteeTokenUrl;
@Value("${gitee.user.url}")
private String giteeUserUrl;
@Value("${gitee.user.prefix}")
private String giteeUserPrefix;
@Override
public String loginByGitee(String code, String state) {
//进行state判断,state的值是前端与后端商定好的,前端将State传给Gitee平台,Gitee平台回传state给回调接口
if(!giteeState.equals(state)) {
throw new UnsupportedOperationException("Invalid state!");
}
//请求Gitee平台获取token,并携带code
String tokenUrl = giteeTokenUrl.concat(code);
JSONObject tokenResponse = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
String token = String.valueOf(tokenResponse.get("access_token"));
System.out.println(token);
//请求用户信息,并携带 token
String userUrl = giteeUserUrl.concat(token);
JSONObject userInfoResponse = HttpClientUtils.execute(userUrl, HttpMethod.GET);
//获取用户信息
String userName = giteeUserPrefix.concat(String.valueOf(userInfoResponse.get("name")));
String password = userName;
//“自动注册” 和登录功能,此处体现了方法的 “复用”
return autoRegisterAndLogin(userName, password);
}
private String autoRegisterAndLogin(String userName, String password) {
//如果第三方账号已经登录过,则直接登录
if(super.checkUserExists(userName)) {
return super.login(userName, password);
}
UserInfo userInfo = new UserInfo();
userInfo.setUserName(userName);
userInfo.setUserPassword(password);
userInfo.setCreateDate(new Date());
//如果第三方账号是第一次登录,先进行“自动注册”
super.register(userInfo);
//自动注册完成后,进行登录
return super.login(userName, password);
}
@Override
public String loginByWechat(String... params) {
return null;
}
@Override
public String loginByQQ(String... params) {
return null;
}
}
三、目标角色
public interface LoginTarget {
public String loginByGitee(String code, String state);
public String loginByWechat(String ... params);
public String loginByQQ(String ... params);
}