正文
设想场景例如 登录策略
1.编写枚举类
public enum LoginEnum { OTHER_PHONE_LOGIN("OTHER", "otherLoginService", "其他手机号登录"), NATIVE_PHONE_LOGIN("NATIVE", "nativeLoginService", "本机登录"), QQ_LOGIN("QQ", "qqLoginService", "QQ登录"), WE_CHAT_LOGIN("WECHAT", "weChatLoginService", "微信登录"),; LoginEnum(String loginType, String serviceName, String desc) { this.loginType = loginType; this.serviceName = serviceName; this.desc = desc; } public static LoginEnum getValue(String loginType) { for (LoginEnum loginEnum : LoginEnum.values()) { if (loginEnum.getLoginType().equals(loginType)) { return loginEnum; } } return LoginEnum.NATIVE_PHONE_LOGIN; } private String loginType; private String serviceName; private String desc; public String getLoginType() { return loginType; } public String getServiceName() { return serviceName; } public String getDesc() { return desc; } }
2.编写登录策略接口类
/** * @Author liuy * @Description 登录策略接口类 * @Date 2021/11/10 14:54 * @Version 1.0 */ public interface LoginInterface { String login(LoginVO loginVO) ; }
3.编写实现类
注意实现类的@Service必须与LoginEmun的serviceName的值一致,这样spring才能根据serviceName找到这个策略
例如:OtherLoginService
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author liuy * @Description 其他手机号登录服务 * @Date 2021/11/10 15:23 * @Version 1.0 */ @Service("otherLoginService") public class OtherLoginService implements LoginInterface{ @Override public String login(String loginType) { return "我是其他手机号登录" } }
4.编写登录环境角色类
import com.soboot.auth.enums.LoginEnum; import com.soboot.auth.service.LoginInterface; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @Author liuy * @Description 登录环境角色类 * @Date 2021/11/10 15:31 * @Version 1.0 */ @Service public class LoginSpringContext { @Autowired private final Map<String, LoginInterface> strategyMap = new ConcurrentHashMap<>(4); /** * 根据登录类型获取不同策略 * @param loginType * @return */ public LoginInterface getService(String loginType) { LoginEnum loginEnum = LoginEnum.getValue(loginType); return strategyMap.get(loginEnum.getServiceName()); } }
这个类的作用是把所有策略 加载到内存
5.调用策略
@Autowired private LoginSpringContext loginSpringContext; /** * 登录通用服务 * * @param loginVO 登录参数 * @return 登录信息 */ public String loginIn(String loginType) { LoginInterface service = loginSpringContext.getService(loginType); String loginTypeName= service.login(loginVO); return loginTypeName; }
当调用这个方法时只需要填入对应的loginType就能实现对应的策略!