策略模式-新玩法

步骤:

创建枚举

public enum MessagePushType {

    DING_TALK("dingtalk", "钉钉"),
    QQ("qq", "QQ"),
    WECHAT("wechat", "微信"),
    WEIBO("weibo", "微博"),
    FEISHU("feishu", "飞书"),
    FACEBOOK("facebook", "脸书"),
    GITHUB("github", "github"),
    ;
    private final String code;
    private final String description;

    MessagePushType(String code, String description) {
        this.code = code;
        this.description = description;
    }


    public String code() {
        return code;
    }

    public String description() {
        return description;
    }

    public static MessagePushType search(String code) {
        Assert.notNull(code, "code不能为空");
        return Arrays.stream(values())
                .filter(value -> code.equals(value.code()))
                .findFirst()
                .orElse(null);
    }

    public static Map<String, MessagePushType> of() {
        return Arrays.stream(MessagePushType.values())
                .collect(Collectors.toMap(MessagePushType::code, Function.identity()));
    }

创建策略接口

public interface MessagePushStrategy {
    Boolean support(MessagePushType type);
    String push(String content);
}

编写策略实现

@Service
public class GitHubProvider implements MessagePushStrategy {
    private static final Logger logger = LoggerFactory.getLogger(GitHubProvider.class);
    /**
     * @param type
     * @return
     */
    @Override
    public Boolean support(MessagePushType type) {
        return type.equals(MessagePushType.GITHUB);
    }

    /**
     * @param content
     * @return
     */
    @Override
    public String push(String content) {
        logger.info("GitHubProvider push content: {} , 枚举 + map + 函数式接口 + InitializingBean 实现的策略模式", content);
        // fixme 这里才是真正的业务逻辑
        // do something
        return content;
    }
}

TOP: 这里可以有多种实现,根据具体需求进行实现

创建策略工厂

public interface StrategyFactory extends InitializingBean {
    String execute(String object, String code);
}

编写策略工厂实现类

@Service
public class StrategyFactoryImpl implements StrategyFactory {
    private static final Logger logger = LoggerFactory.getLogger(StrategyFactoryImpl.class);
    @Resource private List<MessagePushStrategy> pushStrategyServices;
    private final Map<String, MessagePushStrategy> map = new HashMap<>();

    /**
     */
    @Override
    public void afterPropertiesSet() {
        pushStrategyServices.forEach(service -> {
            Map<String, MessagePushType> pushTypeMap = MessagePushType.of();
            pushTypeMap.entrySet().stream()
                    .filter(entry -> service.support(entry.getValue()))
                    .forEach(entry -> map.put(entry.getValue().getCode(), service));
        });
    }

    /**
     * @param object
     * @return
     */
    @Override
    public String execute(String object, String code) {
        MessagePushStrategy pushStrategy = map.get(code);
        if(Objects.isNull(pushStrategy)) {
            logger.error("未找到对应的推送策略");
            // FIXME: 2024/5/18 这里可以抛出自定义的异常
        }
        Boolean support = pushStrategy.support(MessagePushType.search(code));
        if(support) {
            return pushStrategy.push(object);
        }
        // FIXME: 2024/5/18 这里可以抛出自定义的异常
        throw new RuntimeException("不支持该类型");
    }
}

测试用例

@RestController
@RequestMapping(value = "/message/push")
public class MessagePushController {
    @Resource private StrategyFactory strategyFactory;

    @RequestMapping(value = "/type", method = RequestMethod.GET)
    public String push(String content, String type) {
        return strategyFactory.execute(content, type);
    }
}
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值