工厂模式用于干掉大量的if-else
,策略模式用于挪去臃肿的业务代码,还可以进一步升级加上模板模式,以及抽取成Starter
public interface HandlerStrategy extends InitializingBean {
void findSyncOrders();
}
public class SalesPlatformFactory {
private static final Map<String, HandlerStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();
public static HandlerStrategy getInvokeStrategy(String code) {
return STRATEGY_MAP.get(code);
}
public static void register(SalesPlatFormEnum salesPlatFormEnum, HandlerStrategy handlerStrategy) {
if (salesPlatFormEnum == null || handlerStrategy == null) {
return;
}
STRATEGY_MAP.put(salesPlatFormEnum.getCode(), handlerStrategy);
}
}
public class OttoHandler implements HandlerStrategy {
@Override
public void findSyncOrders() {
}
@Override
public void afterPropertiesSet() throws Exception {
SalesPlatformFactory.register(SalesPlatFormEnum.OTTO, this);
}
}
第二版:模板设计模式来啦!
首先,抽象的处理业务的Handler,也就是 “模板”
public abstract class AbstractHandler implements InitializingBean {
// 模板方法1:必须让子类实现的方法
public abstract void mustOverrideMethod();
// 模板方法2:子类可实现可不实现,父类可提供默认的实现
public void defaultMethod() {
System.out.println("父类提供默认的实现,子类也可以覆写");
}
// 模板方法3:有需要的就去实现,但父类不提供实现
public void someNeedOverrideMethod() {
throw new UnsupportedOperationException();
}
}
其次,模板的一种具体实现
@Component
public class OttoHandler extends AbstractHandler {
@Override
public void mustOverrideMethod() {
System.out.println("Otto的必须实现");
}
@Override
public void afterPropertiesSet() {
Factory.register(SalesPlatFormEnum.OTTO, this);
}
}
然后,工厂的注册和生产
public class Factory {
private static final Map<String, AbstractHandler> STRATEGY_MAP = new ConcurrentHashMap<>();
public static AbstractHandler getInvokeStrategy(SalesPlatFormEnum salesPlatFormEnum) {
return STRATEGY_MAP.get(salesPlatFormEnum.getCode());
}
public static void register(SalesPlatFormEnum salesPlatFormEnum, AbstractHandler handler) {
if (salesPlatFormEnum == null || handler == null) {
return;
}
STRATEGY_MAP.put(salesPlatFormEnum.getCode(), handler);
}
}
补充枚举类
@Getter
@AllArgsConstructor
public enum SalesPlatFormEnum {
OTTO("otto");
private final String code;
}
最后,测试方法
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
AbstractHandler handler = Factory.getInvokeStrategy(SalesPlatFormEnum.OTTO);
handler.mustOverrideMethod();
handler.defaultMethod();
handler.someNeedOverrideMethod();
}
}
运行结果: