【设计模式实战】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
     */
    @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);
        }
    
    }
    

三、运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值