策略模式学习

策略模式1

/**
 * 提供业务逻辑单元
 */
@Service
public class BizUnitService {

    public String bizOne(String order) {
        return order + "各种花式操作1";
    }
    public String bizTwo(String order) {
        return order + "各种花式操作2";
    }
    public String bizThree(String order) {
        return order + "各种花式操作3";
    }
}
/**
 * 某个业务服务类
 */
@Service
public class BizService {
    @Autowired
    private BizUnitService bizUnitService;

    private Map<String, Function<String, String>> checkResultDispatcherComX = new HashMap<>();

    /**
     * 初始化 业务逻辑分派Map 其中value 存放的是 lambda表达式
     */
    @PostConstruct
    public void checkResultDispatcherComXInit() {
        checkResultDispatcherComX.put("key_订单1", order -> bizUnitService.bizOne(order));
        checkResultDispatcherComX.put("key_订单1_订单2", order -> bizUnitService.bizTwo(order));
        checkResultDispatcherComX.put("key_订单1_订单2_订单3", order -> bizUnitService.bizThree(order));
    }

    public String getCheckResultComX(String order, int level) {
        //写一段生成key的逻辑:
        String key = getDispatcherComXKey(order, level);

        Function<String, String> result = checkResultDispatcherComX.get(key);
        if (result != null) {
            //执行这段表达式获得String类型的结果
            return result.apply(order);
        }
        return "不在处理的逻辑中返回业务错误";
    }

    /**
     * 判断条件方法
     */
    private String getDispatcherComXKey(String order, int level) {
        StringBuilder key = new StringBuilder("key");
        for (int i = 1; i <= level; i++) {
            key.append("_" + order + i);
        }
        return key.toString();
    }
}

策略模式2

public interface ShareStrategy {
    // 定义分享策略执行方法
    void shareAlgorithm(String param);
}

public class OrderItemShare implements ShareStrategy {
    @Override
    public void shareAlgorithm(String param) {
        System.out.println("当前分享图片是" + param);
    }
}

 // 定义策略map缓存
    private static final Map<String, ShareStrategy> shareStrategies = new HashMap<> ();

    static {
        shareStrategies.put ("order", new OrderItemShare ());
        shareStrategies.put ("single", new SingleItemShare ());
        shareStrategies.put ("multi", new MultiItemShare ());
    }

    // 获取指定策略
    public static ShareStrategy getShareStrategy(String type) {
        if (type == null || type.isEmpty ()) {
            throw new IllegalArgumentException ("type should not be empty.");
        }
        return shareStrategies.get (type);
    }

    public static void main(String[] args) {
        // 测试demo
        String shareType = "order";
        ShareStrategy shareStrategy = ShareFactory.getShareStrategy (shareType);
        shareStrategy.shareAlgorithm ("order");
        // 输出结果:当前分享图片是order
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值