您的位置:首页 > 科技 > IT业 > 策略模式实现

策略模式实现

2024/10/7 4:25:19 来源:https://blog.csdn.net/m0_64372868/article/details/139955844  浏览:    关键词:策略模式实现

文章目录

  • 策略模式
    • 实现
      • 定义接口与实现类
      • map + 函数式编程
      • 使用
    • 总结

策略模式

策略模式就是定义一组策略,每一个策略之间可以相互的替换,可以根据客户端的不同需求调用不同的策略。

实现

定义接口与实现类

public interface UpateStatusChangeStrategy {public Boolean updateUserStatus(Long id);}@Service
public class UserStatusImpl implements UpateStatusChangeStrategy {@Resourceprivate UserMapper userMapper;@Overridepublic Boolean updateUserStatus(Long id) {//校验参数if (id < 0 || id == 0){throw new BusinessException(ErrorCode.PARAMS_ERROR);}User user = userMapper.selectById(id);if (user == null){throw new BusinessException(ErrorCode.PARAMS_ERROR);}//修改状态值user.setUserStatus(0);int  result = userMapper.updateById(user);if (result != 0){return true;}return false;}
}@Service
public class AdminStatusImpl implements UpateStatusChangeStrategy {@Resourceprivate UserMapper userMapper;@Overridepublic Boolean updateUserStatus(Long id) {//校验参数if (id < 0 || id == 0){throw new BusinessException(ErrorCode.PARAMS_ERROR);}User user = userMapper.selectById(id);if (user == null){throw new BusinessException(ErrorCode.PARAMS_ERROR);}//修改状态值user.setUserStatus(1);int  result = userMapper.updateById(user);if (result != 0){return true;}return false;}
}

map + 函数式编程

使用 postConstruct 初始化map

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {private Map<Integer, Function<Long, Boolean>> strategyMap = new HashMap<>();@Resourceprivate UserStatusImpl userStatusImpl;@Resourceprivate AdminStatusImpl adminStatusImpl;@PostConstructpublic void strategyMapInit() {strategyMap.put(1, id -> userStatusImpl.updateUserStatus(id));strategyMap.put(2, id -> adminStatusImpl.updateUserStatus(id));}
}

使用

    /*** 修改用户状态位 -- 使用策略模式** @return*/@PutMapping("/adminStatus")public BaseResponse<Boolean> adminStatus(Long id, Integer type) {if (id <= 0) {throw new BusinessException(ErrorCode.PARAMS_ERROR);}Boolean result = userService.updateUserStatusStrategy(id, type);return ResultUtils.success(result);}}@Overridepublic Boolean updateUserStatusStrategy(Long id, Integer type) {Function<Long, Boolean> function = strategyMap.get(type);if (function == null)throw new BusinessException(ErrorCode.SYSTEM_ERROR);Boolean result = function.apply(id);if (result == null)throw new BusinessException(ErrorCode.SYSTEM_ERROR);return result;}

总结

定义一组策略(通过一个接口+多个实现类),为了减少 if - else 的时候,使用 map + 函数式编程存储策略方法,并且进行初始化。这样就不要使用 if - else 了,如果后期需要使用单例模式的形式,只创建使用的对象,这就下一步的优化的地方

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com