本博客是针对TapJoy的一个积分货币想转换的策略模式
(1)抽象策略类,拥有一个转换和一个执行方法
public interface ConvertStrategy {
public BigDecimal convert(String loginId,Integer credit) throws ConvertException;
public Boolean excute(String loginId,BigDecimal amount) throws ConvertHandlerException;
}
(2)具体策略了,实现抽象策略接口
@Component("defaultConvert")
public class DefaultConvert implements ConvertStrategy {
private static final Logger LOG = LoggerFactory.getLogger(DefaultConvert.class);
@Resource(name = PfingoApiServiceName.TAPJOY_SERVICE)
private TapJoyService TapJoyService;
@Override
public BigDecimal convert(String loginId, Integer credit,String plat,String env) throws ConvertException {
LOG.info("enter convert");
BigDecimal times = new BigDecimal("100");
return (new BigDecimal(credit).multiply(times));
}
@Override
public Boolean excute(String loginId, BigDecimal amount,String plat,String env,String clientIp) throws ConvertHandlerException {
LOG.debug("enter excute");
LOG.debug("loginId:"+loginId);
LOG.debug("amount:"+amount);
LOG.debug("plat:"+plat);
LOG.debug("env:"+env);
LOG.debug("clientIp:"+clientIp);
Map<String, Object> ht = new HashedMap();
ht.put(Constant.CLIENT_IP, clientIp);
ht.put(Constant.LOGIN_ID,loginId);
ht.put("provider_id","SH_CC");
ht.put("amount",amount);
ht.put(Constant.CODE, null);
ht.put(Constant.DESC,null);
try {
TapJoyService.tapTopUp(ht);
} catch (ServiceException e) {
e.printStackTrace();
}
return ht.get(Constant.CODE).equals(StatusConstant.THOUSAND);
}
@PostConstruct
public void register(){
ConvertManager.set("default",this);
}
}
(3)策略容器,持有策略对象
public class CreditConvertHandler {
private ConvertStrategy convertStrategy;
public CreditConvertHandler(String convert) throws ConvertNotFoundException {
convertStrategy = ConvertManager.get(convert);
if (convertStrategy == null){
throw new ConvertNotFoundException(convert+"not found");
}
}
public BigDecimal convert(String loginId,Integer credit,String plat,String env) throws ConvertException{
return convertStrategy.convert(loginId,credit,plat,env);
}
public Boolean excute(String loginId,BigDecimal amount,String plat,String env,String clientIp) throws ConvertHandlerException{
return convertStrategy.excute(loginId,amount,plat,env,clientIp);
}
}
(4)策略管理类,将所有策略对象以Map的形式存放。
public class ConvertManager {
private static final Map<String,ConvertStrategy> map = new HashMap<>();
public static ConvertStrategy get(String convertName){
return map.get(convertName);
}
public static void set(String convertName,ConvertStrategy convertStrategy){
map.put(convertName,convertStrategy);
}
}
(5)使用策略
CreaditConvertHandler creditConvertHandler = new CreditConvertHandler("default");
BigDecimal amount = creditConvertHandler.convert(userId,currentcy,platform,version);
boolean isSuccess = creditConvertHandler.excute(userId,amount,platform,version,clientIp);