-
意圖
定義一系列的算法,并且把它們一個(gè)個(gè)封裝起來,并且使它們可相互替換。而這些算法就被成為一個(gè)個(gè)的策略。
-
動(dòng)機(jī)
很多時(shí)候?qū)⑺惴ㄓ簿幋a到使用它們的類中是不可取的,這時(shí)我們可以定義不同的類來封裝這些算法,從而避免這些問題,一個(gè)以這種方法封裝的算法稱為一個(gè)策略。
-
適用性
1.許多相關(guān)的類僅僅是行為有異?!安呗浴碧峁┝艘环N用多個(gè)行為中的一個(gè)行為來配置一個(gè)類的方法。
2.需要使用一個(gè)算法的不同變體。
3.一個(gè)類定義了多種行為,并且這些行為在這個(gè)類的操作中以多個(gè)條件語句的形式出現(xiàn)。將相關(guān)的條件分支移入它們各自的Strategy類中以代替這些條件語句。
-
真實(shí)的策略
-
JDK源碼文件過濾:
public String[] list(FilenameFilter filter) {
String names[] = list();
if ((names == null) || (filter == null)) {
return names;
}
List<String> v = new ArrayList<>();
for (int i = 0 ; i < names.length ; i++) {
if (filter.accept(this, names[i])) {
v.add(names[i]);
}
}
return v.toArray(new String[v.size()]);
}
public
interface FilenameFilter {
/**
* Tests if a specified file should be included in a file list.
*
* @param dir the directory in which the file was found.
* @param name the name of the file.
* @return <code>true</code> if and only if the name should be
* included in the file list; <code>false</code> otherwise.
*/
boolean accept(File dir, String name);
}
這是java.io.File中的list(FilenameFilter filter)方法,它實(shí)現(xiàn)定義了一個(gè)FilenameFilter接口,讓用戶自己實(shí)現(xiàn)它,從而達(dá)到文件的過濾。
一個(gè)簡(jiǎn)單過濾的例子:
public class DirList
{
public static void main(String[] args)
{
File path = new File(".");
String[] list;
list = path.list(new DirFilter(".java"));
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for(String dirItem: list)
System.out.println(dirItem);
}
}
class DirFilter implements FilenameFilter
{
private Pattern pattern;
public DirFilter(String regex)
{
pattern = pattern.compile(regex);
}
public boolean accept(File dir, String name)
{
return pattern.matcher(name).matches();
}
}
這樣我們就將java文件給過濾出來了。這里每一個(gè)FilenameFilter的實(shí)現(xiàn)都是一種策略,java.io.File.listFiles(FileFilter filter) 同理
-
Lucene中org.apache.lucene.analysis中的TokenStreamComponents的重用策略
/**
* Strategy defining how TokenStreamComponents are reused per call to
* {@link Analyzer#tokenStream(String, java.io.Reader)}.
*/
public static abstract class ReuseStrategy {
/** Sole constructor. (For invocation by subclass constructors, typically implicit.) */
public ReuseStrategy() {}
/**
* Gets the reusable TokenStreamComponents for the field with the given name.
*
* @param analyzer Analyzer from which to get the reused components. Use
* {@link #getStoredValue(Analyzer)} and {@link #setStoredValue(Analyzer, Object)}
* to access the data on the Analyzer.
* @param fieldName Name of the field whose reusable TokenStreamComponents
* are to be retrieved
* @return Reusable TokenStreamComponents for the field, or {@code null}
* if there was no previous components for the field
*/
public abstract TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName);
/**
* Stores the given TokenStreamComponents as the reusable components for the
* field with the give name.
*
* @param fieldName Name of the field whose TokenStreamComponents are being set
* @param components TokenStreamComponents which are to be reused for the field
*/
public abstract void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components);
/**
* Returns the currently stored value.
*
* @return Currently stored value or {@code null} if no value is stored
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final Object getStoredValue(Analyzer analyzer) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
return analyzer.storedValue.get();
}
/**
* Sets the stored value.
*
* @param storedValue Value to store
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final void setStoredValue(Analyzer analyzer, Object storedValue) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
analyzer.storedValue.set(storedValue);
}
}
/**
* A predefined {@link ReuseStrategy} that reuses the same components for
* every field.
*/
public static final ReuseStrategy GLOBAL_REUSE_STRATEGY = new ReuseStrategy() {
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
return (TokenStreamComponents) getStoredValue(analyzer);
}
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
setStoredValue(analyzer, components);
}
};
/**
* A predefined {@link ReuseStrategy} that reuses components per-field by
* maintaining a Map of TokenStreamComponent per field name.
*/
public static final ReuseStrategy PER_FIELD_REUSE_STRATEGY = new ReuseStrategy() {
@SuppressWarnings("unchecked")
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
return componentsPerField != null ? componentsPerField.get(fieldName) : null;
}
@SuppressWarnings("unchecked")
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
if (componentsPerField == null) {
componentsPerField = new HashMap<>();
setStoredValue(analyzer, componentsPerField);
}
componentsPerField.put(fieldName, components);
}
};
定義了一個(gè)抽象重用策略類,然后實(shí)現(xiàn)了兩種重用策略。分別為所有field共用一個(gè)TokenStreamComponent或者每個(gè)field一個(gè)TokenStreamComponent