策略模式实例干货

策略模式的结构

  策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。用一句话来说,就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”。下面就以一个示意性的实现讲解策略模式实例的结构。

  这个模式涉及到三个角色:

  ●  环境(Context)角色:持有一个Strategy的引用。

  ●  抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

  ●  具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。

源码如下:

抽象策略服务类

package com.test.modules.strategy.service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: ThirdProductStrategyService
 * @Description: 第三方商品策略服务
 * @Author: zhangs
 * @Email: 853632587@qq.com
 * @Date: 2020/6/11 11:13
 * @Version: 1.0
 */
public interface ThirdProductStrategyService extends ThirdFlagStrategyService{

    /**
     * 全量同步商品
     */
    void syncAllProduct();

    /**
     * 根据消息接口同步商品
     * @param types
     */
    void syncProductByMessage(String types);


    /**
     * 根据商品第三方sku编码同步商品
     * @param productCode
     * @return
     */
    List<String> syncProductByCodes(String productCode);

    /**
     * 根据商品池进行同步
     * @param catId
     * @return
     */
    Map<String, Object> syncProductByCat(String catId);

}

具体策略实现类:

package com.test.modules.strategy.service.impl;

import com.alibaba.fastjson.JSON;
import com.test.common.Constant;
import com.test.modules.strategy.service.ThirdProductStrategyService;
import com.test.pojo.third.test.TestMessage;
import com.test.pojo.third.test.TestProductResult;
import com.test.service.third.test.TestBaseService;
import com.test.service.third.test.TestSkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @ClassName: ProductToTestServiceImpl
 * @Description: 商品服务
 * @Author: zhangs
 * @Email: 853632587@qq.com
 * @Date: 2020/6/10 11:36
 * @Version: 1.0
 */
@Service
public class ProductToTestServiceImpl implements ThirdProductStrategyService {

    private static final Logger logger = LoggerFactory.getLogger(ProductToTestServiceImpl.class);


    @Autowired(required = false)
    private TestSkuService testSkuService;
    //日志前缀
    private static final String loggerPrefix="Test";
    @Autowired(required = false)
    private TestBaseService testBaseService;
    //商品变动类型2-价格变动 4-上下架变更 6-商品池加减
    private static final Integer[] productTypes = {2,4,6};


    @Override
    public Integer shopId() {
        return Constant.SHOP_BASIC_INFO.Test.getShopId();
    }

    /**
     * 商品同步
     */
    @Override
    public void syncAllProduct() {
    }

    /**
     * 根据消息同步商品
     * @param types 2-商品价格变更 4-商品上下架 6-商品池添加、删减商品 16-商品介绍及规格参数变更
     */
    @Override
    public void syncProductByMessage(String types) {
        logger.info("api {} syncProductByMessage begin. param:{}", loggerPrefix, types);
        if (!StringUtils.isEmpty(types)) {
            List<Integer> delIds = null;
            try {
                for (String type : types.split(",")) {
                    if(Arrays.asList(productTypes).contains(Integer.valueOf(type))){
                        List<TestMessage> messages = TestBaseService.getMessages(null, type);
                        logger.info("api {} syncProductByMessage . result:{}", loggerPrefix, JSON.toJSONString(messages));
                        if (!org.springframework.util.CollectionUtils.isEmpty(messages)) {
                            delIds = new ArrayList<>();
                            TestSkuService.syncProductBySkus(buidSkus(messages, delIds));
                            //对已同步的进行清理
                            if (!org.springframework.util.CollectionUtils.isEmpty(delIds))
                                TestBaseService.delMessages(delIds);
                        }
                    } else{
                        logger.info("api {} syncProductByMessage . type:{} not support", loggerPrefix, type);
                    }
                }
            } catch (Exception e) {
                logger.error("api {} syncProductByMessage error", loggerPrefix, e);
            }
        }
    }

    /**
     * 商品编码构建
     * @param messages
     * @return
     */
    private List<String> buidSkus(List<TestMessage> messages, List<Integer> delIds) {
        List<String> skus = new ArrayList<String>();
        for (TestMessage message : messages) {
            Map<String, Object> params = JSON.parseObject(message.getResult().toString(),Map.class);
            Object oSku = params.get("skuId");
            if (!ObjectUtils.isEmpty(oSku) && !skus.contains(oSku.toString())) {
                skus.add(oSku.toString());
            }
            delIds.add(message.getId());
        }
        return skus;
    }

    /**
     * 根据上商品编码同步商品
     * @param productCode
     * @return
     */
    @Override
    public List<String> syncProductByCodes(String productCode) {
        List<String> syncCodes =null;
        TestProductResult product=TestSkuService.getSkuDetail(productCode);
        if (product != null) {
            syncCodes = new ArrayList<String>(1);
            syncCodes.add(productCode);
            TestSkuService.syncProductBySkus(syncCodes);
        }
        return syncCodes;
    }

    /**
     * 根据商品池同步商品
     * @param catId
     * @return
     */
    @Override
    public Map<String, Object> syncProductByCat(String catId) {
        Map<String,Object> result=new HashMap<>();
        result.put("errorMsg", "不支持商品池同步");
        return result;
    }

}

策略类型:

package com.test.modules.strategy;

import com.test.modules.strategy.service.ThirdOrderStrategyService;
import com.test.modules.strategy.service.ThirdProductStrategyService;

/**
 * @ClassName: StrategyType
 * @Description: 策略类型
 * @Author: zhangs
 * @Email: 853632587@qq.com 
 * @Date: 2020/5/22 14:13
 * @Version: 1.0
 */
public enum StrategyType {

    SHOP_PRODUCT("SHOP_PRODUCT", ThirdProductStrategyService.class),SHOP_ORDER("SHOP_ORDER", ThirdOrderStrategyService.class);

    //类型
    private String type;
    //class
    private Class<?> clazz;

    private StrategyType(String type, Class<?> clazz) {
        this.type = type;
        this.clazz = clazz;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Class<?> getClazz() {
        return clazz;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }

    public static Class<?> getMsg(String type) {

        for (StrategyType v : StrategyType.values()) {

            if (v.getType().equals(type)) {
                return v.getClass();
            }
        }

        return null;
    }
}

环境角色类:

package com.test.modules.strategy;

import com.test.modules.strategy.service.ThirdOrderStrategyService;
import com.test.modules.strategy.service.ThirdProductStrategyService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: StrategyContext
 * @Description: 第三方服务策略
 * @Author: zhangs
 * @Email: 853632587@qq.com
 * @Date: 2020/6/3 9:35
 * @Version: 1.0
 */
@Component
public class StrategyContext implements InitializingBean, ApplicationContextAware{
	
	private ApplicationContext applicationContext;
	
	private Map<String,Map<String,?>> strategyMap = new ConcurrentHashMap<>();

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
	    for(StrategyType type :StrategyType.values()){
            Map<String,?> beanMap = applicationContext.getBeansOfType(type.getClazz());
            this.strategyMap.put(type.getType(),beanMap);
        }
	}

	//第三方商品
	public ThirdProductStrategyService getThirdProductHandler(Integer shopId) {
        Map<String, ThirdProductStrategyService>  beanMap= (Map<String, ThirdProductStrategyService>) strategyMap.get(StrategyType.SHOP_PRODUCT.getType());
        for (String key : beanMap.keySet()) {
            if(beanMap.get(key).shopId().equals(shopId)){
                return beanMap.get(key);
            }
        }
        return null;
    }

	//第三方订单
	public ThirdOrderStrategyService getThirdOrderHandler(Integer shopId) {
		Map<String, ThirdOrderStrategyService>  beanMap= (Map<String, ThirdOrderStrategyService>) strategyMap.get(StrategyType.SHOP_ORDER.getType());
		for (String key : beanMap.keySet()) {
			if(beanMap.get(key).shopId().equals(shopId)){
				return beanMap.get(key);
			}
		}
		return null;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值