美文网首页
@Autowired搭配策略模式

@Autowired搭配策略模式

作者: AC编程 | 来源:发表于2023-02-16 13:40 被阅读0次

一、代码

@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);
    }
}

相关文章

网友评论

      本文标题:@Autowired搭配策略模式

      本文链接:https://www.haomeiwen.com/subject/tzepkdtx.html