【设计模式实战】SpringBoot模板+策略设计模式实现抽奖流程

网友投稿 313 2022-09-19

【设计模式实战】SpringBoot模板+策略设计模式实现抽奖流程

一、需求分析

1. 抽奖余额有两种,1种【货币1】,1种【货币2】,对应扣除两种余额 2. 不变的部分余额和扣除余额,变化的部分是余额类型与扣除方式,所以可以使用策略模式

二、设计模式思想

1. 定义获得余额和扣除余额抽象方法2. 策略方法分为【货币1】策略和【货币2】策略3. 调用放Context根据传入策略执行查询和扣除方法4. 可扩展,新增【货币3】抽奖,则只需要实现LotteryContext接口

二、代码实现

LotteryStrategy

/** * 抽奖策略模式 * 需求分析:抽奖余额有两种,1种金币,1种奖券;不变的部分余额和扣除余额,变化的部分是余额类型与扣除方式,所以可以使用策略模式 * 1. 定义获得余额和扣除余额抽象方法 * 2. 策略方法分为金币策略和奖券策略 * 3. 调用放Context根据传入策略执行查询和扣除方法 * 4. 可扩展,新增钻石抽奖,则只需要实现LotteryContext接口 * @author Marion * @date 2021/7/15 09:59 */public interface LotteryStrategy { /** * 获得抽奖货币 */ long amount(long uid); /** * 扣除抽奖货币 */ boolean draw(long uid, long amoun);}

CoinLotteryStrategy

/** * 金币抽奖模式 * @author Marion * @date 2021/7/15 10:07 */@Componentpublic class CoinLotteryStrategy implements LotteryStrategy { /** * 获得抽奖货币 */ @Override public long amount(long uid) { return 0; } /** * 扣除抽奖货币 * @param uid * @param amount */ @Override public boolean draw(long uid, long amount) { return true; }}

CouponLotteryStrategy

/** * 奖券抽奖模式 * @author Marion * @date 2021/7/15 10:07, */@Componentpublic class CouponLotteryStrategy implements LotteryStrategy { /** * 获得抽奖货币 */ @Override public long amount(long uid) { return 0; } /** * 扣除抽奖货币 * @param uid * @param amount */ @Override public AssetTransaction draw(long uid, long amount) { return true }}

LotteryContext

/** * 抽奖策略模式 * @author Marion * @date 2021/7/15 10:04 */public class LotteryContext { private LotteryStrategy lotteryStrategy; public LotteryContext(LotteryStrategy lotteryStrategy) { this.lotteryStrategy = lotteryStrategy; } public long getAmount(long uid) { return this.lotteryStrategy.amount(uid); } public boolean draw(long uid, long amount) { return this.lotteryStrategy.draw(uid, amount); }}

三、运行结果

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:女研究生做“思维导图”与男友吵架!网友:吵架届的“内卷之王”....
下一篇:151. 翻转字符串里的单词_Java实现_空间O(1)详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~