设计模式4-策略模式

一、概念

行为型模式

在策略模式中,一个类的行为或其算法可以在运行时更改。创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象。策略对象改变context对象的执行算法。

策略模式的用意是针对一组算法,将每一个算法封装到具有共同接口的独立类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

优点:

避免使用多重条件判断

如果没有策略模式,一个策略家族有多个策略算法,一会要使用A策略,一会要使用B策略,怎么设计呢?使用多重if的条件语句?多重条件语句不易维护,而且出错的概率大大增强。

使用策略模式后,简化了操作,同时避免了条件语句判断。

缺点:

客户端必须知道所有的策略类,并自行决定使用 哪一个策略,这意味着客户端必须理解这些算法的区别,以便选择恰当的算法

如果备选策略很多,对象的数据会很多

策略模式实现(分三个部分)

策略模式把对象本身和行为区分开来。

  • 抽象策略类(Strategy):策略的抽象,行为方式的抽象;
  • 具体策略类(ConcreteStrategy):具体的策略实现,每一种行为方式的具体实现;
  • 环境类(Context):持有Strategy对象,用来封装具体行为,操作策略的上下文环境。

 

二、实现示例

按照策略模式的三个部分,我们定义了一个ReosurceQueryStrategy接口和实现了ResourceQueryStrategy接口的实体类。Context是一个持有ResourceQueryStrategy对象的使用了某种策略的类

ResourceQueryStrategy.java(interface)

1 public interface ResourceQueryStrategy {
2    public ResourceBo query(queryCondition cond);
3 }
View Code

FlightQuery.java

1 public class FlightQuery implements ResourceQueryStrategy{
2    @Override
3    public ResourceBo query(QueryCondition cond) {
4       return ...
5    }
6 }
View Code

HotelQuery.java

1 public class HotelQuery implements ResourceQueryStrategy{
2    @Override
3    public ResourceBo query(QueryCondition cond) {
4       return ...
5    }
6 }
View Code

Context.java

 1 public class Context {
 2    private ResourceQueryStrategy strategy;
 3  
 4    public Context(ResourceQueryStrategy strategy){
 5       this.strategy = strategy;
 6    }
 7  
 8    public int executeStrategy(QueryCondition cond){
 9       return strategy.query(cond);
10    }
11 }
View Code

使用 Context 来查看当它改变策略 Strategy 时的行为变化。

public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new FlightQuery()); 
      context = new Context(new HotelQuery());  
   }
}

注意 :以上具体策略对象都是new出来,而实际运用应该通过spring来管理,这样才能做到真正的开闭原则。下面会在举例。

若是采用Spring来管理,以上的具体实现类以及Context可以变更下。

先定义一个注解:

/**
* 资源类型
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResourceCategory {
String resourceTypeId();
}

具体实现类:

@Component
@ResourceCategory(resourceTypeId= "1")
public class FlightQuery  implements ResourceQueryStrategy
{
      @Override
      public ResourceBo query(QueryCondition cond)
      {
          //具体实现逻辑
      }
}
@Component
@ResourceCategory(resourceTypeId= "2")
public class HotelQuery  implements ResourceQueryStrategy
{
      @Override
      public ResourceBo query(QueryCondition cond)
      {
          //具体实现逻辑
      }
}

context类:/**

 * 负责和具体的策略类交互 动态的切换不同的算法
*/
@Component
public class Context implements ApplicationContextAware { @Autowired ApplicationContext applicationContext;
//策略接口
private static Map<String, Class<ResourceQueryStrategy>> strategyMap = Maps.newConcurrentMap();
/**
* 初始化 把这几个活动的示例 初始化的时候就装到一个map集合中
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { //获取所有策略注解的Bean Map<String, Object> resourceProcessStrategyMap = applicationContext.getBeansWithAnnotation(ResourceCategory.class); if (MapUtils.isNotEmpty(resourceProcessStrategyMap)) { resourceProcessStrategyMap.forEach((k, v) -> { Class<ResourceQueryStrategy> strategyClass = (Class<ResourceQueryStrategy>) v.getClass(); String resourceTypeId = strategyClass.getAnnotation(ResourceCategory.class).resourceTypeId(); strategyMap.put(resourceTypeId , strategyClass); }); } }
/**
* 获取具体策略
*/
public ResourceQueryStrategy ResourceVerificationQueryStrategy(String value){ Class<ResourceQueryStrategy> strategyClass = strategyMap.get(value); if (strategyClass == null) { //如果为空先用默认处理逻辑处理 String defaultKey = 10; strategyClass = strategyMap.get(defaultKey ); if (strategyClass == null) { throw new IllegalArgumentException(String.format("can't find valid resource, value: %s", value)); } } return applicationContext.getBean(strategyClass); }

若不采用可以采用Spring的ApplicationContextAware, 可以采用@PostConstruct, 在类初始化的时候将所有的策略封装到一个map集合中。

实际场景

如付款方式(一般分为银联、微信、支付宝)、订单下各种资源的查询(酒店、机票、签证...)、优惠券活动(满减送、限时折扣、包邮活动,拼团)等等

通过以上示例应该明白,策略模式的重心不是如何实现算法(就如同工厂模式的重心不是工厂中如何产生具体子类一样),而是如何组织、调用这些算法,从而让程序结构更灵活,具有更好的维护性和扩展性。

策略模式有一个很大的特点就是各策略算法的平等性。对于一系列具体的策略算法,大家的地位是完全一样的,正因为这个平等性,各个算法之间才可以相互替换。

运行期间,每一个时刻只能使用一个具体的策略实现对象,虽然可以动态地在不同的策略中实现切换。

三、策略模式在Java中的应用以及解读

 策略模式在Java中的应用,这个太明显了,因为Comparator这个接口简直就是为策略模式而生的。比方说Collections里面有一个sort方法,因为集合里面的元素有可能是复合对象,复合对象并不像基本数据类型,可以根据大小排序,复合对象怎么排序呢?基于这个问题考虑,Java要求如果定义的复合对象要有排序的功能,就自行实现Comparable接口或Comparator接口,看一下sort带Comparator的重载方法(Comparator就是一个抽象的策略;一个类实现该结构,并实现里面的compare方法,该类成为具体策略类;Collections类就是环境角色,他将集合的比较封装成静态方法对外提供api,在调用的时候传入具体实现的比较算法,即策略):

1 public static <T> void sort(List<T> list, Comparator<? super T> c) {
2     Object[] a = list.toArray();
3     Arrays.sort(a, (Comparator)c);
4     ListIterator i = list.listIterator();
5     for (int j=0; j<a.length; j++) {
6         i.next();
7         i.set(a[j]);
8     }
9     }

跟一下第3行:

1 public static <T> void sort(T[] a, Comparator<? super T> c) {
2     T[] aux = (T[])a.clone();
3         if (c==null)
4             mergeSort(aux, a, 0, a.length, 0);
5         else
6             mergeSort(aux, a, 0, a.length, 0, c);
7     }

传入的c不为null,跟一下第6行的mergeSort:

 1 private static void mergeSort(Object[] src,
 2                   Object[] dest,
 3                   int low, int high, int off,
 4                   Comparator c) {
 5     int length = high - low;
 6 
 7     // Insertion sort on smallest arrays
 8     if (length < INSERTIONSORT_THRESHOLD) {
 9         for (int i=low; i<high; i++)
10         for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
11             swap(dest, j, j-1);
12         return;
13     }
14 
15         // Recursively sort halves of dest into src
16         int destLow  = low;
17         int destHigh = high;
18         low  += off;
19         high += off;
20         int mid = (low + high) >>> 1;
21         mergeSort(dest, src, low, mid, -off, c);
22         mergeSort(dest, src, mid, high, -off, c);
23 
24         // If list is already sorted, just copy from src to dest.  This is an
25         // optimization that results in faster sorts for nearly ordered lists.
26         if (c.compare(src[mid-1], src[mid]) <= 0) {
27            System.arraycopy(src, low, dest, destLow, length);
28            return;
29         }
30 
31         // Merge sorted halves (now in src) into dest
32         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
33             if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
34                 dest[i] = src[p++];
35             else
36                 dest[i] = src[q++];
37         }
38     }

第10行,根据Comparator接口实现类的compare方法的返回结果决定是否要swap(交换)。

这就是策略模式,我们可以给Collections的sort方法传入不同的Comparator的实现类作为不同的比较策略。不同的比较策略,对同一个集合,可能会产生不同的排序结果。

原文地址:https://www.cnblogs.com/dudu2mama/p/14149239.html