1.定义基类接口:
public interface IModelParamStrategy extends InitializingBean {
void checkParam(HttpContextDto httpContextDto);
}
2.定义抽象类,实现策略接口
定义一个抽象类 AbstractModelParamStrategy,它实现了部分 IModelParamStrategy 接口的功能,并留出 checkParam方法需要被具体策略实现类实现
public abstract class AbstractModelParamStrategy implements IModelParamStrategy {
@Override
public abstract void checkParam(HttpContextDto httpContextDto);
}
3.具体的策略实现类
public class ChatParamStrategyV1 extends AbstractModelParamStrategy {
@Override
public void checkParam(HttpContextDto httpContextDto) {
}
@Override
public void afterPropertiesSet() throws Exception {
StrategyFactory.register("chat", this);
}
}
4.实现策略工厂类
public class StrategyFactory {
/**
* 存放特殊策略的工厂,使用名称注册
*/
private static Map<String, IModelParamStrategy> nameFactory = new ConcurrentHashMap<>(1);
public static void register(String name, IModelParamStrategy strategy) {
if (Objects.isNull(name) || Objects.isNull(strategy)) {
throw new RuntimeException("参数不能为空!");
}
if (nameFactory.containsKey(name)) {
throw new RuntimeException(String.format("%s类型已被注册!", name));
}
nameFactory.put(name, strategy);
}
public static IModelParamStrategy get(String name) {
if (!nameFactory.containsKey(name)) {
throw new RuntimeException(name + "类型未支持!");
}
return nameFactory.get(name);
}
}
控制类:
IModelParamStrategy paramStrategy = StrategyFactory.get("chat");
paramStrategy.checkParam(httpContextDto);