工厂模式+策略模式实践
- 业务需求:根据传入的订单信息,不同类型的产品分别走不同的处理方式。
- 业务流程
- 技术设计:使用工厂模式+策略模式进行业务的处理
- 代码实现
public class TestService{
public static void main(String[] args) {
ProductOrderInfo productOrderInfo = new ProductOrderInfo();
ProductStrategy productStrategy = ProductStrategyFactory.getProductStrategy(productOrderInfo.getProductType);
ProductHandler productHandler = new ProductHandler(productStrategy);
productHandler.handler(productOrderInfo);
}
}
public class ProductOrderInfo {
private ProductType productType;
······
}
@Component
public class ProductStrategyFactory implements InitializingBean {
@Autowired
private List<ProductStrategy> productStrategies;
private static Map<ProductType, ProductStrategy> productStrategyMap;
@Override
public void afterPropertiesSet() throws Exception {
productStrategyMap = productStrategies.stream().collect(Collectors
.toMap(ProductStrategy::getProductType, Function.identity()));
}
public static ProductStrategy getProductStrategy(ProductType productType) {
if (productType == null ) {
throw new Exception("productType不能为空!");
}
return productStrategyMap.get(productType);
}
}
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface ProductStrategy {
ProductType getProductType();
boolean processProduct(ProductOrderInfo productOrderInfo);
@Component
public class AlphaProductStrategy implements ProductStrategy {
@Override
public ProductType getProductType() {
return ProductType.ALPHA;
}
@Override
public boolean processProduct(ProductOrderInfo productOrderInfo) {
}
}
@Component
public class BetaProductStrategy implements ProductStrategy {
@Override
public ProductType getProductType() {
return ProductType.BETA;
}
@Override
public boolean processProduct(ProductOrderInfo productOrderInfo) {
}
}
@Component
public class GammaProductStrategy implements ProductStrategy {
@Override
public ProductType getProductType() {
return ProductType.GAMMA;
}
@Override
public boolean processProduct(ProductOrderInfo productOrderInfo) {
}
}
@Getter
public enum ProductType {
ALPHA(0, "α"),
BETA(1, "β"),
GAMMA(2, "γ");
private Integer code;
private String desc;
public class ProductHandler{
private ProductStrategy productStrategy;
public ProductHandler(ProductStrategy productStrategy){
this.productStrategy = productStrategy;
}
public Boolean handler(ProductOrderInfo productOrderInfo) {
boolean result = productStrategy.processProduct(productOrderInfo);
}
}