美文网首页
策略模式

策略模式

作者: 悲伤的大橙子 | 来源:发表于2019-07-17 17:45 被阅读0次

模式分析

每个类封装一种策略,为了保证这些策略的一致性,用一个抽象的策略类来做业务定义。 业务系统中的策略模式.png
  • OrderProcessor: 构建上下文参数,根据参数获取策略
  • StrategyHandler: 业务抽象策略类
    private static final List<AbstractStrategy> INSTANCE = Lists.newArrayList();
    定义获取策略方法:
 public static getStrategy(OrderDetailDO context) {
     for(Iterator<AbstractStrategy> it = INSTANCE.iterator();it.hasNext(); ){
         AbstractStrategy strategy = it.next();
         if(strategy.matchStrategy(context)){
              return strategy;
         }
      }
      return null;
 }

定义注册方法:

 public static synchronized void register(AbstractStrategy strategy){
     INSTANCE.add(strategy);
     Collections.sort(INSTANCE, new Comparator<AbstractStrategy>(){
         @Override
         public int compare(AbstractStrategy o1, AbstractStrategy o2){
             return o1.getPriority().compareTo(o2.getPriority());
         }
     });
  }
  • AbstractStrategy及实现类: 进行具体注册,写入策略优先级和策略匹配规则,处理每个策略类不同的业务逻辑。

难点

如何确定什么时候用哪个策略呢?

ApplicationContext动态注册:获取注入Spring的名称,用于注册过程中从Spring中获取bean,从而AOP等注解可以生效。

@Resource
private ApplicationContext applicationContext;
AbstractStrategy strategy = (AbstractStrategy)applicationContext.getBean(getBeanName());

注册完成即向策略队列INSTANCE中加入一个新的策略类,按每个策略类的优先级进行排序。

相关文章

网友评论

      本文标题:策略模式

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