策略模式实战:Spring中动态选择商品处理策略的实现
概念
可以在运行时期动态的选择需要的具体策略类,处理具体的问题
组成元素
策略接口
public interface GoodsStrategy {void handleGoods();
}
具体策略类
@Service(Constants.BEAN_GOODS)
public class BeanGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("处理金豆啦~~~~~");}
}
@Service(Constants.MEMBER_GOODS)
public class MemberGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("会员商品");}
}
@Service(Constants.MEMBER_PLUS_GOODS)
public class MemberPlusGoodsStrategy implements GoodsStrategy {@Overridepublic void handleGoods() {System.out.println("会员积分商品");}
}
上下文工厂类
@Service
public class GoodsStrategyFactory {@Autowiredprivate 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 接口的具体实现类的实例。
获取策略类处理业务
@Testvoid test() {GoodsStrategy goodsStrategy = goodsStrategyFactory.getGoodsStrategy(Constants.MEMBER_GOODS);if (goodsStrategy != null){goodsStrategy.handleGoods();}}