Controller层
@RequestMapping("/storeRecharge")
@RestController
@Api(value="扫一扫二维码功能管理",description = "提供查询二维码是否正确")
public class StoreRechargeController {
private static Logger log = LoggerFactory.getLogger(LoginController.class);
@Autowired
private QrCodeContext qrCodeContext;
@ApiOperation("获取二维码信息")
@RequestMapping("/searchQrCodeIsTrue")
public String searchQrCode(@RequestParam(value = "qrCode") String qrCode,
@RequestParam(value = "istrue", defaultValue = "") String istrue,
@RequestParam(value = "username", defaultValue = "") String username
){
JSONObject jsonobject1 = JSONObject.parseObject(qrCode);
String key = jsonobject1.getString("key");
String value = jsonobject1.getString("value");
JSONObject json = new JSONObject();
try {
if ("true".equals(istrue)){
String qc = qrCodeContext.QcCode(key, value, username);
json.put("key",key);
json.put("value",qc);
return json.toString();
} else {
return qrCodeContext.SelectQcCode(key,value,username);
}
} catch (Exception e) {
e.printStackTrace();
log.info("@@=======>>>>二维码key不正确,获取不到对应的二维码策略类");
json.put("msg","二维码格式不正确");
json.put("state",0);
return json.toString();
}
}
Service层 (策略类的上下文类)
package com.mise.dm.pattern.qrstrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service // 注意这儿得是@Service
public class QrCodeContext {
/*
AutoWired一个
Map<String, QrCodeStrategy>
就会在初始化的时候将所有的Strategy自动加载到Map中
而使用ConcurrentHashMap,是为了保证线程安全(虽然完全没有用到多线程...)
*/
@Autowired
Map<String, QrCodeStrategy> strategyMap = new ConcurrentHashMap<>();
/**
* 操作二维码
* @param value
* @param username
* @return
*/
public String QcCode(String key,String value,String username){
return strategyMap.get(key).QcCode(value,username);
}
/**
* 查询二维码信息
* @param value
* @param username
* @return
*/
public String SelectQcCode(String key,String value, String username){
return strategyMap.get(key).SelectQcCode(value,username);
}
}
策略类1
/**
* 优惠券策略
*/
@Component("coupon") //这儿是注入bean, bean的名字就是引号里面的 ,比如这个就是: coupon
public class CouponStrategy implements QrCodeStrategy{
...
public String QcCode(String value,String username) {
//业务逻辑
}
public String SelectQcCode(String value,String username) {
//业务逻辑
}
}
策略类2
/**
* 商品核实策略
*/
@Component("pickGoods")
public class PickGoodsStrategy implements QrCodeStrategy {
...
/**
* 处理二维码状态
*
* @param value
* @return
*/
public String QcCode(String value,String username) {
...
}
/**
* 查询二维码信息
*
* @param value
* @return
*/
public String SelectQcCode(String value,String username) {
...
}
}