public class PassportTest {
public static void main(String[] args) {
IPassportForThird passportForThird = new PassportForThirdAdapter();
passportForThird.loginForQQ("");
}
}
/**
* 只扩展
* Created by Tom on 2019/3/16.
*/
public interface IPassportForThird {
/**
* QQ登录
* @param id
* @return
*/
ResultMsg loginForQQ(String id);
/**
* 微信登录
* @param id
* @return
*/
ResultMsg loginForWechat(String id);
/**
* 记住登录状态后自动登录
* @param token
* @return
*/
ResultMsg loginForToken(String token);
/**
* 手机号登录
* @param telphone
* @param code
* @return
*/
ResultMsg loginForTelphone(String telphone, String code);
/**
* 注册后自动登录
* @param username
* @param passport
* @return
*/
ResultMsg loginForRegist(String username, String passport);
}
/**
* 结合策略模式、工厂模式、适配器模式
*/
public class PassportForThirdAdapter extends SiginService implements IPassportForThird {
@Override
public ResultMsg loginForQQ(String id) {
return processLogin(id,LoginForQQAdapter.class);
}
@Override
public ResultMsg loginForWechat(String id) {
return processLogin(id,LoginForWechatAdapter.class);
}
@Override
public ResultMsg loginForToken(String token) {
return processLogin(token,LoginForTokenAdapter.class);
}
@Override
public ResultMsg loginForTelphone(String telphone, String code) {
return processLogin(telphone,LoginForTelAdapter.class);
}
@Override
public ResultMsg loginForRegist(String username, String passport) {
super.regist(username,passport);
return super.login(username,passport);
}
private ResultMsg processLogin(String key,Class<? extends LoginAdapter> clazz){
try{
//适配器不一定要实现接口
LoginAdapter adapter = clazz.newInstance();
//判断传过来的适配器是否能处理指定的逻辑
if(adapter.support(adapter)){
return adapter.login(key,adapter);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
//类图的快捷键 Ctrl + Alt + Shift + U
}
/**
* 在适配器里面,这个接口是可有可无,不要跟模板模式混淆
* 模板模式一定是抽象类,而这里仅仅只是一个接口
* Created by Tom on 2019/3/16.
*/
public interface LoginAdapter {
boolean support(Object adapter);
ResultMsg login(String id,Object adapter);
}
public class LoginForQQAdapter implements LoginAdapter {
@Override
public boolean support(Object adapter) {
return adapter instanceof LoginForQQAdapter;
}
@Override
public ResultMsg login(String id, Object adapter) {
return null;
}
}
public class LoginForSinaAdapter implements LoginAdapter {
@Override
public boolean support(Object adapter) {
return adapter instanceof LoginForSinaAdapter;
}
@Override
public ResultMsg login(String id, Object adapter) {
return null;
}
}
适配器模式
最新推荐文章于 2024-07-31 22:15:00 发布