服务提供者框架适用于”服务有多个实现”的解耦, 比如商城平台接口有淘宝, 天猫, 京东等多实现.
这里拿商城接口做示例, 结构如下图
- MallServiceProvider中进行服务注册
- MallService作为顶层服务接口, 当然还可以进一步根据业务功能细分, 比如OrderService ,ProductService(extends MallService) 等等
- AbstractMallServic作为接口的抽象实现, 定义算法骨架, 提取具体实现中通用的操作, 比如通用校验等
MallServiceProvider
@Component
public class MallServiceProvider {
private static final Map<MallType, MallService> MALL_SERVICE_MAP = new ConcurrentHashMap<>();
public MallServiceProvider(List<MallService> mallServices) {
for (MallService mallService : mallServices) {
for (MallType mallType : mallService.supports()) {
MALL_SERVICE_MAP.put(mallType, mallService);
}
}
}
public MallService getMallService(MallType mallType) {
return MALL_SERVICE_MAP.getOrDefault(mallType, MALL_SERVICE_MAP.get(MallType.DEFAULT));
}
}
MallService
/**
* @author xinzhang
* @date 2021/1/29 14:09
*/
public interface MallService {
/**
* 示例方法
*/
void demoFunction();
/**
* 支持哪些平台
*
* @return
*/
MallType[] supports();
}
AbstractMallService
/**
* @author xinzhang
* @date 2021/1/29 14:11
*/
public abstract class AbstractMallService implements MallService {
@Override
public void demoFunction() {
System.out.println("一些通用校验以及处理, 巴拉巴拉");
doDemoFunction();
}
/**
* 具体实现
*/
protected abstract void doDemoFunction();
}
DefaultMallService
@Component
public class DefaultMallService extends AbstractMallService {
@Override
protected void doDemoFunction() {
}
@Override
public MallType[] supports() {
return new MallType[]{
MallType.DEFAULT
};
}
}
JdMallService
@Component
public class JdMallService extends AbstractMallService {
@Override
protected void doDemoFunction() {
System.out.println("这里是京东商城服务");
}
@Override
public MallType[] supports() {
return new MallType[]{
MallType.JD
};
}
}
TaoBaoMallService
@Component
public class TaoBaoMallService extends AbstractMallService {
@Override
protected void doDemoFunction() {
System.out.println("这里是淘宝, 天猫平台服务");
}
@Override
public MallType[] supports() {
return new MallType[]{
MallType.TAOBAO, MallType.TMALL
};
}
}
MallType枚举
public enum MallType {
DEFAULT("默认空实现", 0),
TAOBAO("淘宝", 1),
TMALL("天猫", 2),
JD("京东", 3);
private final String caption;
private final int value;
MallType(String caption, int value) {
this.caption = caption;
this.value = value;
}
public int value() {
return this.value;
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private MallServiceProvider mallServiceProvider;
@Test
public void testConfiguration() {
MallService mallService = mallServiceProvider.getMallService(MallType.TAOBAO);
mallService.demoFunction();
}
}
--------------输出
一些通用校验以及处理, 巴拉巴拉
这里是淘宝, 天猫平台服务