SpringBoot工厂模式----构造方式
interface
public interface MallTypeHandle {
void check(Store store);
MallType[] supports();
}
@Component
public class JDMallTypeHandle implements MallTypeHandle {
@Override
public void check(Store store) {
Assert.mustNotEmpty(store.getSettingJson(), StoreError.PARAM_SETTING_NOT_EMPTY);
JdStoreSetting setting = JsonUtils.toObject(store.getSettingJson(), JdStoreSetting.class);
Assert.mustNotNull(setting.getJdType(), StoreError.JD_TYPE_NOT_EMPTY);
}
@Override
public MallType[] supports() {
return new MallType[]{MallType.JD};
}
}
factory
@Component
public class MallTypeHandleFactory {
@Resource
private DefaultMallTypeHandleAbstract defaultMallTypeHandle;
private final HashMap<MallType, MallTypeHandle> map = new HashMap<>();
@Autowired
public MallTypeHandleFactory(List<MallTypeHandle> mallTypeHandles){
mallTypeHandles.forEach(x->{
MallType[] supports = x.supports();
for (int i=0;i<supports.length;i++){
map.put(supports[i],x);
}
});
}
public MallTypeHandle getHandle(MallType mallType){
return map.getOrDefault(mallType,defaultMallTypeHandle);
}
}