龙空技术网

java开发中实际使用的责任链设计模式

老莫摸鱼 65

前言:

此时各位老铁们对“java项目责任描述”大体比较着重,同学们都想要了解一些“java项目责任描述”的相关内容。那么小编也在网络上汇集了一些有关“java项目责任描述””的相关资讯,希望我们能喜欢,小伙伴们快快来了解一下吧!

1.创建一个抽象类,方便责任规则传递。

抽象类中,抽象类作为自己的属性。并创建一个抽象方法;

eg:

public abstract class RuleHandler {

public RuleHandler successor;

public RuleHandler getSuccessor() {

return successor;

}

public void setSuccessor(RuleHandler successor) {

this.successor = successor;

}

public abstract ApiResponse handlerRequest(RuleDto rule);

}

2.实现抽象类方法。写自定义类自己的逻辑。

eg:

3.多个责任类实现抽象类方法,书写各自逻辑代码

4.责任链核心代码引用。

eg:

@Service

public class KruleService {

private static final Logger LOG = LoggerFactory.getLogger(KruleService.class);

@Autowired

private RuleMapper ruleMapper;

@Autowired

private CheckTotalPrize checkTotalPrize;

@Autowired

private CheckFristHitPrize checkFristHitPrize;

@Autowired

private CheckMaxHitTime checkMaxHitTime;

@Autowired

private CheckHitRule checkHitRule;

@Autowired

private WinnerInfoMapper winnerInfoMapper;

/**

* 抽奖规则校验

* @param userId

* @return

*/

public ApiResponse checkRule(Integer userId,Integer userFriendsId){

ApiResponse<Object> response = new ApiResponse<>();

// 获取有效的一个奖品规则

RuleDto rule = this.ruleMapper.getVaildRuleOne();

if(!Optional.ofNullable(rule).isPresent()){

response.setMsg(ErrorResultEnum.NO_PRIZE_RULE.getMsg());

response.setCode(ErrorResultEnum.NO_PRIZE_RULE.getCode());

return response;

}

rule.setUserFriendsId(userFriendsId);

rule.setUserId(userId);

// 查询中奖纪录

WinnerInfo winnerInfo = this.winnerInfoMapper.findWinnerInfoByFrindsId(userFriendsId);

LOG.info("查询中奖纪录:{}",winnerInfo);

if(Optional.ofNullable(winnerInfo).isPresent()){

String couponsCode = winnerInfo.getCouponsCode();

if(StringUtils.isEmpty(couponsCode)){

response.setMsg(ErrorResultEnum.NO_HIT_PRIZE.getMsg());

response.setCode(ErrorResultEnum.NO_HIT_PRIZE.getCode());

}else{

response.setMsg(ErrorResultEnum.HIT_PRIZE.getMsg().replace("XXXX",couponsCode));

response.setCode(ErrorResultEnum.HIT_PRIZE.getCode());

}

return response;

}

// 1.总奖品校验

checkTotalPrize.setSuccessor(checkFristHitPrize);

// 2.首次必中校验

checkFristHitPrize.setSuccessor(checkMaxHitTime);

// 3.每人最多中奖校验

checkMaxHitTime.setSuccessor(checkHitRule);

return checkTotalPrize.handlerRequest(rule);

}

}

标签: #java项目责任描述