spring设计模式实现不同会员不同折扣

9 篇文章 0 订阅

直接附源码:

//订单生成类

public interface OrderService {
    public void createOrder();
}

//订单生成业务类

package com.huanwu.sp.salecard.web.controller.ordertest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private PayMoney payMoney;

    @Override
    public void createOrder() {
        double d = payMoney.getMoney("normal", 100);
        System.out.println(d);
    }

}
 

---策略模式,不同的类型,不同的折扣

//折扣接口

package com.huanwu.sp.salecard.web.controller.ordertest;

public interface DiscountService {
    public String type();
    
    public double discount(double fee);
}
//普通会员

package com.huanwu.sp.salecard.web.controller.ordertest;

import org.springframework.stereotype.Service;

@Service
public class NormalDiscount implements DiscountService {

    @Override
    public String type() {
        return "normal";
    }

    @Override
    public double discount(double fee) {
        return fee * 0.9;
    }

}
//vip会员

package com.huanwu.sp.salecard.web.controller.ordertest;

import org.springframework.stereotype.Service;

@Service
public class VipDiscount implements DiscountService {

    @Override
    public String type() {
        return "vip";
    }

    @Override
    public double discount(double fee) {
        return fee * 0.8;
    }

}
 

//计算折扣类

package com.huanwu.sp.salecard.web.controller.ordertest;

import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class PayMoney {

    // public double getMoney(String type, double fee) {
    // if ("normal".equals(type)) {
    // // 如果是普通会员
    // return fee * 1;
    // } else if ("vip".equals(type)) {
    // // 如果是vip会员
    // return fee * 0.8;
    // } else {
    // return fee * 1.1;
    // }
    // }

//此处为最主要的一段代码
    HashMap<String, DiscountService> map = new HashMap<>();

    public PayMoney(List<DiscountService> list) {
        for (DiscountService discountService : list) {
            map.put(discountService.type(), discountService);
        }
    }

    public double getMoney(String type, double fee) {
        return map.get(type).discount(fee);
    }

}
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值