马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
概念
可以在运行时期动态的选择需要的具体策略类,处理具体的题目
构成元素
策略接口
- public interface GoodsStrategy {
- void handleGoods();
- }
复制代码 具体策略类
- @Service(Constants.BEAN_GOODS)
- public class BeanGoodsStrategy implements GoodsStrategy {
- @Override
- public void handleGoods() {
- System.out.println("处理金豆啦~~~~~");
- }
- }
复制代码- @Service(Constants.MEMBER_GOODS)
- public class MemberGoodsStrategy implements GoodsStrategy {
- @Override
- public void handleGoods() {
- System.out.println("会员商品");
- }
- }
复制代码- @Service(Constants.MEMBER_PLUS_GOODS)
- public class MemberPlusGoodsStrategy implements GoodsStrategy {
- @Override
- public void handleGoods() {
- System.out.println("会员积分商品");
- }
- }
复制代码 上下文工厂类
- @Service
- public class GoodsStrategyFactory {
- @Autowired
- private Map<String, GoodsStrategy> goodsStrategyMap;
- public GoodsStrategy getGoodsStrategy(String goodsType) {
- return goodsStrategyMap.get(goodsType);
- }
- }
复制代码 解释
在Spring框架中,通过 @Autowired 注入的 Map<String, GoodsStrategy> 会自动将 GoodsStrategy 接口的所有实现类注入到Map中,此中:
- Key:Bean的名称(默认是类名首字母小写,或通过 @Component("自定义名称") 指定)。
- Value:GoodsStrategy 接口的具体实现类的实例。
获取策略类处理业务
- @Test
- void test() {
- GoodsStrategy goodsStrategy = goodsStrategyFactory.getGoodsStrategy(Constants.MEMBER_GOODS);
- if (goodsStrategy != null){
- goodsStrategy.handleGoods();
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |