一 枚举类
csharp
@Getter
public enum AuthTypeEnum {
QCT_PASSWORD("qct_password", "密码"),
MOBILE("mobile", "验证码");
public final String code;
public final String desc;
AuthTypeEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public static AuthTypeEnum getByCode(String codeVal) {
for (AuthTypeEnum resultCodeEnum : AuthTypeEnum.values()) {
if (resultCodeEnum.code.equals(codeVal)) {
return resultCodeEnum;
}
}
return null;
}
}
二 抽象策略类
csharp
public abstract class AbstractLoginService {
public static String login( String authType) {
Map<String, AbstractLoginService> LoginServices = ApplicationConfiguration.getBeansOfType(AbstractLoginService.class);
for (AbstractLoginService loginService : LoginServices.values()) {
if (loginService.getType().equals(authType)) {
loginService.doLogin(authType);
return loginService.loginFinal(authType);
}
}
throw new RuntimeException("无效的登录方式");
}
public abstract String getType();
protected abstract void doLogin(String authType);
protected abstract String loginFinal(String authType);
}
三 具体策略实现类
csharp
@Slf4j
@Service
public class CaptchaLoginService extends AbstractLoginService {
@Override
public String getType() {
return AuthTypeEnum.MOBILE.getCode();
}
@Override
protected void doLogin(String authType) {
log.info("验证码登录");
}
@Override
protected String loginFinal(String authType) {
return authType;
}
}
csharp
@Slf4j
@Component
public class PasswordLoginService extends AbstractLoginService {
@Override
public String getType() {
return AuthTypeEnum.QCT_PASSWORD.getCode();
}
@Override
protected void doLogin(String authType) {
log.info("密码登录");
}
@Override
protected String loginFinal(String authType) {
return authType;
}
}
四 应用上下文配置
csharp
@Configuration
public class ApplicationConfiguration implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
return applicationContext.getBeansOfType(clazz);
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
ApplicationConfiguration.applicationContext = applicationContext;
}
}
五单元测试
csharp
@SpringBootTest
class LoginTest {
@Test
void loginPasswordTest() {
String loginType = AuthTypeEnum.QCT_PASSWORD.code;
String login = AbstractLoginService.login(loginType);
System.out.println("login = " + login);
}
@Test
void loginCaptchaTest() {
String loginType = AuthTypeEnum.MOBILE.code;
String login = AbstractLoginService.login(loginType);
System.out.println("login = " + login);
}
}