策略模式解决ifelse判断实际应用场景
1、业务场景
根据志愿者角色判断确定需要给志愿者账户的积分。
2、上代码- 添加志愿者策略接口VolunteerStrategy
添加志愿者策略接口VolunteerStrategy ,策略接口新增一个给志愿者添加积分或者处理其他业务的方法
public interface VolunteerStrategy {
/**
* 不同志愿者角色的用户给与其个人和组织对应不同比例的积分
* @param volunteerParameter
*/
void addVolunteerIntegralToTimeBank(VolunteerParameter volunteerParameter);
}
策略方法参数对象
package com.ehe.elder.domain;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotBlank;
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@Accessors(chain = true)
public class VolunteerParameter {
@ApiModelProperty(value = "志愿者角色{helpAge=助老志愿者,silverAge=银龄志愿者。。。。。")
private String volunteerType;
@ApiModelProperty(value = "收入积分,收入方积分")
private Double integralAdd;
@ApiModelProperty(value = "志愿者关联的用户ID")
private String principalId;
@ApiModelProperty(value = "志愿者姓名")
private String volunteerName;
@ApiModelProperty(value = "老人关联的用户ID")
private String elderPrincipalId;
@ApiModelProperty(value = "支出积分,支出方积分")
private Double integralReduce;
@ApiModelProperty(value = "公益时间")
private Double publicTimes;
@ApiModelProperty(value = "组织ID")
private String organizationId;
@ApiModelProperty(value = "组织名称")
private String organizationName;
//ElderConstant.BUSINESS_TYPE
@NotBlank(message = "业务场景不能为空")
@ApiModelProperty(value = "业务场景,ElderConstant.BUSINESS_TYPE")
private String businessType;
@ApiModelProperty(value = "数据来源ID")
private String sourceId;
@ApiModelProperty(value = "描述")
private String description;
@ApiModelProperty(value = "年龄")
private Integer age;
}
3、创建构造器-VolunteerGranterBuilder
构造器的目的是为了创建对象,先创建一个map集合,将需要传入的志愿者角色作为key,根据志愿者角色来确定需要走哪个策略的实现类去处理对应角色的逻辑。
package com.ehe.elder.builder;
import com.ehe.core.util.SpringUtil;
import com.ehe.elder.strategy.VolunteerStrategy;
import com.ehe.elder.service.impl.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class VolunteerGranterBuilder {
private static Map<String, VolunteerStrategy> strategyMap = new ConcurrentHashMap<>();
static {
strategyMap.put(VolunteerHelpOldGranter.GRANT_TYPE, SpringUtil.getBean(VolunteerHelpOldGranter.class));
strategyMap.put(VolunteerFreeGranter.GRANT_TYPE,SpringUtil.getBean(VolunteerFreeGranter.class));
strategyMap.put(VolunteerPractitionerGranter.GRANT_TYPE,SpringUtil.getBean(VolunteerPractitionerGranter.class));
strategyMap.put(VolunteerWelfareGranter.GRANT_TYPE,SpringUtil.getBean(VolunteerWelfareGranter.class));
strategyMap.put(VolunteerSilverbellGranter.GRANT_TYPE,SpringUtil.getBean(VolunteerSilverbellGranter.class));
}
public static VolunteerStrategy getVolunteerType(String volunteerType){
VolunteerStrategy volunteerStrategy = strategyMap.get(volunteerType);
if (volunteerStrategy == null) {
throw new RuntimeException("no volunteerType was found(未获取到志愿者标签)");
} else {
return volunteerStrategy;
}
}
}
SpringUtil获取spring容器中的对象
package com.ehe.core.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring bean 获取,工具类
* @author rambo
*/
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
/**
* 获取spring容器中的bean, 通过bean名称获取
* @param name bean名称
* @return bean 实例
*/
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
/**
* 获取spring容器中的bean, 通过bean类型获取
* @param clazz bean 类型
* @return T 返回指定类型的bean实例
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
/**
* 获取spring容器中的bean, 通过bean名称和bean类型精确获取
* @param name bean 名称
* @param clazz bean 类型
* @return T 返回指定类型的bean实例
*/
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
}
4、最后创建实现类-VolunteerHelpOldGranter
package com.ehe.elder.service.impl;
import com.ehe.elder.domain.VolunteerParameter;
import com.ehe.elder.enumeration.ElderConstant;
import com.ehe.elder.service.TimeBankPushService;
import com.ehe.elder.strategy.VolunteerStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class VolunteerHelpOldGranter implements VolunteerStrategy {
//助老志愿者
public static final String GRANT_TYPE = "helpAge";
@Autowired
private TimeBankPushService timeBankPushService;
@Override
public void addVolunteerIntegralToTimeBank(VolunteerParameter volunteerParameter) {
//省略业务逻辑
}
private void onlinePay(VolunteerParameter volunteerParameter) {
//省略业务逻辑
}
}
5、创建策略实现类-VolunteerPractitionerGranter
package com.ehe.elder.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ehe.elder.domain.Institution;
import com.ehe.elder.domain.VolunteerInfo;
import com.ehe.elder.domain.VolunteerParameter;
import com.ehe.elder.enumeration.ElderConstant;
import com.ehe.elder.service.InstitutionService;
import com.ehe.elder.service.TimeBankPushService;
import com.ehe.elder.service.VolunteerInfoService;
import com.ehe.elder.strategy.VolunteerStrategy;
import com.ehe.identity.manager.OrganizationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Optional;
@Component
public class VolunteerPractitionerGranter implements VolunteerStrategy {
//养老从业者(非公益)
public static final String GRANT_TYPE = "practitioner";
@Autowired
private TimeBankPushService timeBankPushService;
@Autowired
private InstitutionService institutionService;
@Autowired
private VolunteerInfoService volunteerInfoService;
@Autowired
private OrganizationManager organizationManager;
@Override
public void addVolunteerIntegralToTimeBank(VolunteerParameter volunteerParameter) {
switch (volunteerParameter.getBusinessType()){
case ElderConstant.BUSINESS_TYPE.CASE:
cash(volunteerParameter);
break;
case ElderConstant.BUSINESS_TYPE.ONLINE_PAY:
onlinePay(volunteerParameter);
break;
case ElderConstant.BUSINESS_TYPE.ELDER_FOR_SERVICE:
elderForService(volunteerParameter);
break;
default:
}
}
//为老服务工单处理
private synchronized void elderForService(VolunteerParameter volunteerParameter) {
、、、、、、、省略逻辑
}
//一键通、老人下单工单在线付款或者线上支付处理
private synchronized void onlinePay(VolunteerParameter volunteerParameter) {
//加服务时长
、、、、、、、省略逻辑
}
//一键通、老人下单工单收现金
private synchronized void cash(VolunteerParameter volunteerParameter) {
//给个人加服务时长
、、、、、、、省略逻辑
}
}
6、调用构造器创建对象,通过对象实现对应角色的志愿者业务逻辑-
VolunteerGranterBuilder.getVolunteerType(volunteerInfo.getVolunteerType());
public String pushScoreToTimeBank(ElderJobOrder elderJobOrder) {
try {
//查询志愿者信息
VolunteerInfo volunteerInfo = volunteerInfoService.getByPrincipalId(elderJobOrder.getServiceStaffPrincipalId());
if (ObjectUtils.isEmpty(volunteerInfo)){
return "评价失败:未获取到志愿者信息";
}
//记录志愿者积分,根据服务类型来获取积分
Double integral = volunteerInfo.getIntegral() == null ? 0d : volunteerInfo.getIntegral();
//当前服务所得积分
Double nowIntegral = 0d;
//查询当前服务对应积分
PolicyServerType policyServerType = policyServerTypeService.selectOne(new LambdaQueryWrapper<PolicyServerType>()
.eq(PolicyServerType::getCode, elderJobOrder.getServiceType())
.eq(PolicyServerType::getStatus, ElderConstant.NUMBER.ONE));
if (!ObjectUtils.isEmpty(policyServerType)) {
nowIntegral = policyServerType.getServerScore().doubleValue();
}
Double serviceTime = volunteerInfo.getServiceTime() == null ? 0D : volunteerInfo.getServiceTime();
Double activityTime = Double.valueOf(Duration.between(elderJobOrder.getServiceTime(), elderJobOrder.getCompleteTime()).toMinutes());
//最小最大服务时长计算
activityTime = getActivityTime(activityTime, policyServerType);
//服务时长
volunteerInfo.setServiceTime(serviceTime + activityTime);
volunteerInfo.setIntegral(integral + nowIntegral);
volunteerInfo.setTotalIntegral((volunteerInfo.getTotalIntegral() == null ? 0L : volunteerInfo.getTotalIntegral()) + nowIntegral);
elderJobOrder.setIntegral(nowIntegral);
//修改志愿者信息积分和时间银行 , 未老工单不给志愿者添加积分和服务时长
if (!ElderConstant.SERVICE_CATEGETORY.SERVICE_ELDER.equals(elderJobOrder.getServiceCategory())) {
volunteerInfoService.updateById(volunteerInfo);
//保存志愿者积分记录和时间银行记录
JSONObject jsonObject = new JSONObject();
jsonObject.put("startTime", TimeUtils.ldtToStandardString(elderJobOrder.getServiceTime()));
jsonObject.put("endTime", TimeUtils.ldtToStandardString(elderJobOrder.getCompleteTime()));
jsonObject.put("serviceName", policyServerType.getServerType());
VolunteerStrategy volunteerStrategy = VolunteerGranterBuilder.getVolunteerType(volunteerInfo.getVolunteerType());
volunteerStrategy.addVolunteerIntegralToTimeBank(
VolunteerParameter.builder().build()
.setPrincipalId(volunteerInfo.getPrincipalId())
.setVolunteerName(volunteerInfo.getName())
.setVolunteerType(volunteerInfo.getVolunteerType())
.setAge(ValidateIDCard.getAgeByIdCard(volunteerInfo.getIdNo()))
.setIntegralAdd(nowIntegral)
.setPublicTimes(activityTime)
.setDescription(jsonObject.toJSONString())
.setSourceId(elderJobOrder.getId())
.setBusinessType(ElderConstant.BUSINESS_TYPE.ONLINE_PAY));