一、代码
@Autowired
自动装配多个实例
/**
* 推送策略类
*/
public interface IPushStrategy {
/**
* @param userId:用户ID
* @param msg:推送消息
* @param supplier:推送供应商
* @return
*/
boolean push(Long userId, String msg, String supplier);
}
/**
* 华为推送策略
*/
@Service
public class HuaWeiPushService implements IPushStrategy {
@Override
public boolean push(Long userId, String msg, String supplier) {
if ("HuaWei".equals(supplier)) {
System.out.println("华为推送给用户" + userId + ",推送消息:" + msg);
return true;
}
return false;
}
}
/**
* Oppo推送策略
*/
@Service
public class OppoPushService implements IPushStrategy {
@Override
public boolean push(Long userId, String msg, String supplier) {
if ("Oppo".equals(supplier)) {
System.out.println("Oppo推送给用户" + userId + ",推送消息:" + msg);
return true;
}
return false;
}
}
/**
* 小米推送策略
*/
@Service
public class XiaoMiPushService implements IPushStrategy {
@Override
public boolean push(Long userId, String msg, String supplier) {
if ("XiaoMi".equals(supplier)) {
System.out.println("小米推送给用户" + userId + ",推送消息:" + msg);
return true;
}
return false;
}
}
/**
* 推送策略context
*/
@Component
public class PushContext implements IPushStrategy {
@Autowired
private List<IPushStrategy> pushStrategyList;
@Override
public boolean push(Long userId, String msg, String supplier) {
boolean supplierMatched = false;
for (IPushStrategy pushStrategy : pushStrategyList) {
supplierMatched = pushStrategy.push(userId, msg, supplier);
if (supplierMatched) {
break;
}
}
return supplierMatched;
}
}
@Api(tags = "推送策略模式")
@RestController
@RequestMapping("strategy")
public class TestController {
@Resource
private PushContext pushContext;
@ApiOperation(value = "推送")
@GetMapping("push")
public boolean push() {
Long userId = 273L;
String msg = "您有新的订单";
String supplier = "HuaWei";
//调用的是华为推送实现策略
return pushContext.push(userId, msg, supplier);
}
}
网友评论