概述
策略模式(Strategy)
它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
结构图
实例
1、声明策略类
package com.gc.strategy.core;
public abstract class AbstractSortStrategy {
public static final String DESC = "desc"; // 降序
public static final String ASC = "asc"; // 升序
public void sort(int a[], String order) {
if (a == null) {
throw new IllegalArgumentException("array can not be null");
}
if (order.equals(ASC)) {
asc(a);
} else if (order.equals(DESC)) {
desc(a);
}
}
protected

本文介绍了策略模式,它将算法家族封装并允许相互替换,确保算法变化不影响客户端。文章通过实例展示了如何声明策略类、实现具体策略、创建Context对象及测试用例,最后呈现了输出结果。
最低0.47元/天 解锁文章
538

被折叠的 条评论
为什么被折叠?



