一、需求分析
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 */ @Component public 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, */ @Component public 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); } }